ggml-vulkan.cpp 802 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. // We use VULKAN_HPP_DEFAULT_DISPATCHER, but not VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  10. // to avoid conflicts with applications or other libraries who might use it.
  11. #if VK_HEADER_VERSION >= 301
  12. namespace vk::detail { class DispatchLoaderDynamic; }
  13. using vk::detail::DispatchLoaderDynamic;
  14. #else
  15. namespace vk { class DispatchLoaderDynamic; }
  16. using vk::DispatchLoaderDynamic;
  17. #endif
  18. DispatchLoaderDynamic & ggml_vk_default_dispatcher();
  19. #define VULKAN_HPP_DEFAULT_DISPATCHER ggml_vk_default_dispatcher()
  20. #include <vulkan/vulkan.hpp>
  21. #include <algorithm>
  22. #include <cmath>
  23. #include <iomanip>
  24. #include <iostream>
  25. #include <tuple>
  26. #include <vector>
  27. #include <sstream>
  28. #include <utility>
  29. #include <memory>
  30. #include <limits>
  31. #include <map>
  32. #include <set>
  33. #include <unordered_map>
  34. #include <memory>
  35. #include <mutex>
  36. #include <future>
  37. #include <thread>
  38. #if defined(_MSC_VER)
  39. # define NOMINMAX 1
  40. # include <windows.h>
  41. # define YIELD() YieldProcessor()
  42. #elif defined(__clang__) || defined(__GNUC__)
  43. # if defined(__x86_64__) ||defined(__i386__)
  44. # include <immintrin.h>
  45. # define YIELD() _mm_pause()
  46. # elif defined(__arm__) || defined(__aarch64__)
  47. # if defined(__clang__)
  48. # include <arm_acle.h>
  49. # define YIELD() __yield()
  50. # else
  51. # define YIELD() asm volatile("yield")
  52. # endif
  53. # endif
  54. #endif
  55. #if !defined(YIELD)
  56. #define YIELD()
  57. #endif
  58. #include "ggml-impl.h"
  59. #include "ggml-backend-impl.h"
  60. #include "ggml-vulkan-shaders.hpp"
  61. // remove this once it's more widely available in the SDK
  62. #if !defined(VK_KHR_shader_bfloat16)
  63. #define VK_KHR_shader_bfloat16 1
  64. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  65. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  66. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  67. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  68. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  69. VkStructureType sType;
  70. void* pNext;
  71. VkBool32 shaderBFloat16Type;
  72. VkBool32 shaderBFloat16DotProduct;
  73. VkBool32 shaderBFloat16CooperativeMatrix;
  74. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  75. #endif
  76. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  77. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  78. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  79. #define VK_VENDOR_ID_AMD 0x1002
  80. #define VK_VENDOR_ID_APPLE 0x106b
  81. #define VK_VENDOR_ID_INTEL 0x8086
  82. #define VK_VENDOR_ID_NVIDIA 0x10de
  83. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  84. #define GGML_VK_MAX_NODES 8192
  85. #define VK_CHECK(err, msg) \
  86. do { \
  87. vk::Result err_ = (err); \
  88. if (err_ != vk::Result::eSuccess) { \
  89. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  90. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  91. exit(1); \
  92. } \
  93. } while (0)
  94. #ifdef GGML_VULKAN_DEBUG
  95. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  96. #else
  97. #define VK_LOG_DEBUG(msg) ((void) 0)
  98. #endif // GGML_VULKAN_DEBUG
  99. struct ggml_backend_vk_context;
  100. #define MAX_PARAMETER_COUNT 12
  101. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  102. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  103. struct vk_pipeline_struct {
  104. std::string name;
  105. vk::ShaderModule shader_module;
  106. vk::PipelineLayout layout;
  107. vk::Pipeline pipeline;
  108. uint32_t push_constant_size;
  109. uint32_t parameter_count;
  110. std::array<uint32_t, 3> wg_denoms;
  111. uint32_t align;
  112. // true if fields have been set by ggml_vk_create_pipeline
  113. bool initialized {};
  114. // set to true to request the pipeline is compiled
  115. std::atomic<bool> needed {};
  116. // set to true when the shader has been compiled
  117. std::atomic<bool> compiled {};
  118. // number of registers used, extracted from pipeline executable properties
  119. uint32_t register_count {};
  120. };
  121. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  122. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  123. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  124. struct vk_matmul_pipeline_struct {
  125. vk_pipeline l, m, s;
  126. vk_pipeline a_l, a_m, a_s;
  127. // Returns true when all unaligned pipelines are null.
  128. // We only check for unaligned variants since one of the unaligned pipelines must exist
  129. // while aligned pipelines are optional
  130. bool is_empty() const {
  131. return l == nullptr && m == nullptr && s == nullptr;
  132. }
  133. };
  134. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  135. struct vk_matmul_pipeline2 {
  136. vk_matmul_pipeline2() {
  137. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  139. }
  140. vk_matmul_pipeline f32acc;
  141. vk_matmul_pipeline f16acc;
  142. };
  143. struct vk_device_struct;
  144. typedef std::shared_ptr<vk_device_struct> vk_device;
  145. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  146. struct vk_buffer_struct;
  147. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  148. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  149. struct ggml_backend_vk_buffer_type_context {
  150. std::string name;
  151. vk_device device;
  152. };
  153. struct vk_queue;
  154. // Stores command pool/buffers. There's an instance of this
  155. // for each (context,queue) pair and for each (device,queue) pair.
  156. struct vk_command_pool {
  157. void init(vk_device& device, vk_queue *q_);
  158. void destroy(vk::Device& device);
  159. vk::CommandPool pool;
  160. uint32_t cmd_buffer_idx;
  161. std::vector<vk::CommandBuffer> cmd_buffers;
  162. vk_queue *q;
  163. };
  164. // Prevent simultaneous submissions to the same queue.
  165. // This could be per vk_queue if we stopped having two vk_queue structures
  166. // sharing the same vk::Queue.
  167. static std::mutex queue_mutex;
  168. struct vk_queue {
  169. uint32_t queue_family_index;
  170. vk::Queue queue;
  171. vk_command_pool cmd_pool;
  172. vk::PipelineStageFlags stage_flags;
  173. bool transfer_only;
  174. // copy everything except the cmd_pool
  175. void copyFrom(vk_queue &other) {
  176. queue_family_index = other.queue_family_index;
  177. queue = other.queue;
  178. stage_flags = other.stage_flags;
  179. transfer_only = other.transfer_only;
  180. }
  181. };
  182. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  183. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  184. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  186. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  187. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  188. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  189. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  190. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  191. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  192. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  193. /* .is_host = */ NULL,
  194. };
  195. #ifdef GGML_VULKAN_MEMORY_DEBUG
  196. class vk_memory_logger;
  197. #endif
  198. class vk_perf_logger;
  199. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  200. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx);
  201. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  202. static constexpr uint32_t p021_max_gqa_ratio = 8;
  203. enum vk_device_architecture {
  204. OTHER,
  205. AMD_GCN,
  206. AMD_RDNA1,
  207. AMD_RDNA2,
  208. AMD_RDNA3,
  209. INTEL_XE2,
  210. NVIDIA_PRE_TURING,
  211. };
  212. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  213. vk::PhysicalDeviceProperties props = device.getProperties();
  214. if (props.vendorID == VK_VENDOR_ID_AMD) {
  215. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  216. bool amd_shader_core_properties = false;
  217. bool integer_dot_product = false;
  218. bool subgroup_size_control = false;
  219. for (const auto& properties : ext_props) {
  220. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  221. amd_shader_core_properties = true;
  222. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  223. integer_dot_product = true;
  224. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  225. subgroup_size_control = true;
  226. }
  227. }
  228. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  229. return vk_device_architecture::OTHER;
  230. }
  231. vk::PhysicalDeviceProperties2 props2;
  232. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  233. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  234. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  235. props2.pNext = &shader_core_props_amd;
  236. shader_core_props_amd.pNext = &integer_dot_props;
  237. integer_dot_props.pNext = &subgroup_size_control_props;
  238. device.getProperties2(&props2);
  239. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  240. return vk_device_architecture::AMD_GCN;
  241. }
  242. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  243. // RDNA
  244. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  245. return vk_device_architecture::AMD_RDNA1;
  246. }
  247. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  248. return vk_device_architecture::AMD_RDNA3;
  249. }
  250. return vk_device_architecture::AMD_RDNA2;
  251. }
  252. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  253. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  254. bool subgroup_size_control = false;
  255. for (const auto& properties : ext_props) {
  256. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  257. subgroup_size_control = true;
  258. }
  259. }
  260. if (!subgroup_size_control) {
  261. return vk_device_architecture::OTHER;
  262. }
  263. vk::PhysicalDeviceProperties2 props2;
  264. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  265. props2.pNext = &subgroup_size_control_props;
  266. device.getProperties2(&props2);
  267. if (subgroup_size_control_props.minSubgroupSize == 16) {
  268. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  269. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  270. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  271. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  272. return vk_device_architecture::INTEL_XE2;
  273. }
  274. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  275. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  276. bool cooperative_matrix = false;
  277. // Detect "pre-turing" based on lack of coopmat support.
  278. for (const auto& properties : ext_props) {
  279. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  280. cooperative_matrix = true;
  281. break;
  282. }
  283. }
  284. if (!cooperative_matrix) {
  285. return vk_device_architecture::NVIDIA_PRE_TURING;
  286. }
  287. }
  288. return vk_device_architecture::OTHER;
  289. }
  290. enum vk_conv_shapes {
  291. CONV_SHAPE_128x128,
  292. CONV_SHAPE_64x32,
  293. CONV_SHAPE_32x256,
  294. CONV_SHAPE_COUNT,
  295. };
  296. struct vk_conv_block_size {
  297. uint32_t K;
  298. uint32_t NPQ;
  299. uint32_t CRS;
  300. };
  301. vk_conv_block_size vk_conv_block_sizes[CONV_SHAPE_COUNT] = {
  302. // K NPQ CRS
  303. { 128, 128, 16 }, // CONV_SHAPE_128x128
  304. { 64, 32, 32 }, // CONV_SHAPE_64x32
  305. { 32, 256, 16 }, // CONV_SHAPE_32x256
  306. };
  307. enum dmmv_wg_sizes {
  308. DMMV_WG_SIZE_SUBGROUP,
  309. DMMV_WG_SIZE_LARGE,
  310. DMMV_WG_SIZE_COUNT,
  311. };
  312. enum FaCodePath {
  313. FA_SCALAR,
  314. FA_COOPMAT1,
  315. FA_COOPMAT2,
  316. };
  317. struct vk_fa_pipeline_state {
  318. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, bool small_cache, FaCodePath path, bool aligned, bool f32acc)
  319. : HSK(HSK), HSV(HSV), small_rows(small_rows), small_cache(small_cache), path(path), aligned(aligned), f32acc(f32acc) {}
  320. uint32_t HSK, HSV;
  321. bool small_rows, small_cache;
  322. FaCodePath path;
  323. bool aligned;
  324. bool f32acc;
  325. bool operator<(const vk_fa_pipeline_state &b) const {
  326. return std::tie(HSK, HSV, small_rows, small_cache, path, aligned, f32acc) <
  327. std::tie(b.HSK, b.HSV, b.small_rows, b.small_cache, b.path, b.aligned, b.f32acc);
  328. }
  329. };
  330. struct vk_conv2d_pipeline_state {
  331. vk_conv2d_pipeline_state(uint32_t s0, uint32_t s1, uint32_t p0, uint32_t p1, uint32_t d0, uint32_t d1, uint32_t KW, uint32_t KH)
  332. : s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), KW(KW), KH(KH) {}
  333. uint32_t s0, s1, p0, p1, d0, d1, KW, KH;
  334. bool operator<(const vk_conv2d_pipeline_state &b) const {
  335. return std::tie(s0, s1, p0, p1, d0, d1, KW, KH) <
  336. std::tie(b.s0, b.s1, b.p0, b.p1, b.d0, b.d1, b.KW, b.KH);
  337. }
  338. };
  339. struct vk_solve_tri_pipeline_state {
  340. vk_solve_tri_pipeline_state(uint32_t N, uint32_t K)
  341. : N(N), K(K) {}
  342. uint32_t N, K;
  343. bool operator<(const vk_solve_tri_pipeline_state &b) const {
  344. return std::tie(N, K) <
  345. std::tie(b.N, b.K);
  346. }
  347. };
  348. enum shader_reduction_mode {
  349. SHADER_REDUCTION_MODE_SHMEM,
  350. SHADER_REDUCTION_MODE_HYBRID,
  351. SHADER_REDUCTION_MODE_SUBGROUP,
  352. SHADER_REDUCTION_MODE_COUNT,
  353. };
  354. // argsort pipelines for up to 1<<10 invocations per workgroup
  355. static constexpr uint32_t num_argsort_pipelines = 11;
  356. static constexpr uint32_t num_topk_moe_pipelines = 10;
  357. static constexpr uint32_t num_topk_pipelines = 11;
  358. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  359. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  360. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  361. GGML_OP_RESHAPE };
  362. static constexpr std::initializer_list<ggml_op> topk_moe_sigmoid_norm_bias{ GGML_OP_UNARY, GGML_OP_RESHAPE, GGML_OP_ADD,
  363. GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS,
  364. GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP,
  365. GGML_OP_DIV, GGML_OP_RESHAPE };
  366. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  367. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  368. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  369. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  370. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  371. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  372. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  373. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  374. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  375. //node #982 ( GET_ROWS): ffn_moe_weights-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 (re ( 0K) [Vulka ] ffn_moe_topk-15 ( 0K) [Vulka ]
  376. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  377. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  378. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  379. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  380. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  381. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  382. { 1, 0, 0 }, // reshape->src[0] == softmax
  383. { 2, 0, 0 }, // argsort->src[0] == softmax
  384. { 3, 0, 2 }, // view->src[0] == argsort
  385. { 4, 0, 1 }, // get_rows->src[0] == reshape
  386. { 4, 1, 3 }, // get_rows->src[1] == view
  387. { 5, 0, 4 }, // reshape->src[0] == get_rows
  388. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  389. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  390. { 8, 0, 5 }, // div->src[0] == reshape
  391. { 8, 1, 7 }, // div->src[1] == clamp
  392. { 9, 0, 8 }, // reshape->src[0] == div
  393. };
  394. //node #436 ( UNARY): ffn_moe_probs-10 ( 256K) [Vulka ] use=2: ffn_moe_logits-10 ( 256K) [Vulka ]
  395. //node #437 ( RESHAPE): ffn_moe_probs-10 (re ( 256K) [Vulka ] use=1: ffn_moe_probs-10 ( 256K) [Vulka ]
  396. //node #438 ( ADD): ffn_moe_probs_biased ( 256K) [Vulka ] use=1: ffn_moe_probs-10 ( 256K) [Vulka ] blk.10.exp_probs_b.b ( 0K) [Vulka ]
  397. //node #439 ( ARGSORT): ffn_moe_argsort-10 ( 256K) [Vulka ] use=1: ffn_moe_probs_biased ( 256K) [Vulka ]
  398. //node #440 ( VIEW): ffn_moe_topk-10 ( 255K) [Vulka ] use=3: ffn_moe_argsort-10 ( 256K) [Vulka ]
  399. //node #441 ( GET_ROWS): ffn_moe_weights-10 ( 12K) [Vulka ] use=1: ffn_moe_probs-10 (re ( 256K) [Vulka ] ffn_moe_topk-10 ( 255K) [Vulka ]
  400. //node #442 ( RESHAPE): ffn_moe_weights-10 ( ( 12K) [Vulka ] use=2: ffn_moe_weights-10 ( 12K) [Vulka ]
  401. //node #443 ( SUM_ROWS): ffn_moe_weights_sum- ( 2K) [Vulka ] use=1: ffn_moe_weights-10 ( ( 12K) [Vulka ]
  402. //node #444 ( CLAMP): ffn_moe_weights_sum_ ( 2K) [Vulka ] use=1: ffn_moe_weights_sum- ( 2K) [Vulka ]
  403. //node #445 ( DIV): ffn_moe_weights_norm ( 12K) [Vulka ] use=1: ffn_moe_weights-10 ( ( 12K) [Vulka ] ffn_moe_weights_sum_ ( 2K) [Vulka ]
  404. //node #446 ( RESHAPE): ffn_moe_weights_norm ( 12K) [Vulka ] use=1: ffn_moe_weights_norm ( 12K) [Vulka ]
  405. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_sigmoid_norm_bias_edges {
  406. { 1, 0, 0 }, // reshape->src[0] == sigmoid
  407. { 2, 0, 0 }, // add->src[0] == sigmoid
  408. { 3, 0, 2 }, // argsort->src[0] == add
  409. { 4, 0, 3 }, // view->src[0] == argsort
  410. { 5, 0, 1 }, // get_rows->src[0] == reshape
  411. { 5, 1, 4 }, // get_rows->src[1] == view
  412. { 6, 0, 5 }, // reshape->src[0] == get_rows
  413. { 7, 0, 6 }, // sum_rows->src[0] == reshape
  414. { 8, 0, 7 }, // clamp->src[0] == sum_rows
  415. { 9, 0, 6 }, // div->src[0] == reshape
  416. { 9, 1, 8 }, // div->src[1] == clamp
  417. {10, 0, 9 }, // reshape->src[0] == div
  418. };
  419. // same as early_softmax_norm but ending after the get_rows
  420. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  421. { 1, 0, 0 }, // reshape->src[0] == softmax
  422. { 2, 0, 0 }, // argsort->src[0] == softmax
  423. { 3, 0, 2 }, // view->src[0] == argsort
  424. { 4, 0, 1 }, // get_rows->src[0] == reshape
  425. { 4, 1, 3 }, // get_rows->src[1] == view
  426. };
  427. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  428. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  429. //node #654 ( GET_ROWS): ffn_moe_weights-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 (re ( 0K) [Vulka ] ffn_moe_topk-11 ( 0K) [Vulka ]
  430. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  431. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  432. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  433. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  434. { 1, 0, 0 }, // view->src[0] == argsort
  435. { 2, 1, 1 }, // get_rows->src[1] == view
  436. { 3, 0, 2 }, // reshape->src[0] == get_rows
  437. { 4, 0, 3 }, // soft_max->src[0] == reshape
  438. { 5, 0, 4 }, // reshape->src[0] == soft_max
  439. };
  440. enum topk_moe_mode {
  441. TOPK_MOE_EARLY_SOFTMAX,
  442. TOPK_MOE_EARLY_SOFTMAX_NORM,
  443. TOPK_MOE_LATE_SOFTMAX,
  444. TOPK_MOE_SIGMOID_NORM_BIAS,
  445. TOPK_MOE_COUNT,
  446. };
  447. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  448. { 1, 0, 0 }, // view->src[0] == rope
  449. { 2, 0, 1 }, // set_rows->src[0] == view
  450. };
  451. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  452. { 1, 0, 0 }, // mul->src[0] == rms
  453. { 2, 0, 1 }, // rope->src[0] == mul
  454. { 3, 0, 2 }, // view->src[0] == rope
  455. { 4, 0, 3 }, // set_rows->src[0] == view
  456. };
  457. struct vk_device_struct {
  458. std::recursive_mutex mutex;
  459. vk::PhysicalDevice physical_device;
  460. vk::PhysicalDeviceProperties properties;
  461. std::string name;
  462. uint64_t max_memory_allocation_size;
  463. uint64_t max_buffer_size;
  464. uint64_t suballocation_block_size;
  465. uint64_t min_imported_host_pointer_alignment;
  466. bool external_memory_host {};
  467. bool fp16;
  468. bool bf16;
  469. bool pipeline_robustness;
  470. bool memory_priority;
  471. vk::Device device;
  472. uint32_t vendor_id;
  473. vk::DriverId driver_id;
  474. vk_device_architecture architecture;
  475. vk_queue compute_queue;
  476. vk_queue transfer_queue;
  477. bool single_queue;
  478. bool support_async;
  479. uint32_t subgroup_size;
  480. uint32_t subgroup_size_log2;
  481. uint32_t shader_core_count;
  482. bool uma;
  483. bool prefer_host_memory;
  484. bool float_controls_rte_fp16;
  485. bool subgroup_basic;
  486. bool subgroup_arithmetic;
  487. bool subgroup_shuffle;
  488. bool subgroup_ballot;
  489. bool subgroup_clustered;
  490. bool subgroup_vote;
  491. bool multi_add;
  492. bool shader_int64;
  493. bool buffer_device_address;
  494. bool vulkan_memory_model;
  495. bool add_rms_fusion;
  496. uint32_t partials_binding_alignment;
  497. bool integer_dot_product;
  498. // 0: default, 1: force mmvq, -1: disable mmvq
  499. int32_t mmvq_mode;
  500. bool subgroup_size_control;
  501. uint32_t subgroup_min_size;
  502. uint32_t subgroup_max_size;
  503. bool subgroup_require_full_support;
  504. // floor(log2(maxComputeWorkGroupInvocations))
  505. uint32_t max_workgroup_size_log2 {};
  506. bool coopmat_support;
  507. bool coopmat_acc_f32_support {};
  508. bool coopmat_acc_f16_support {};
  509. bool coopmat_bf16_support {};
  510. bool coopmat_support_16x16x16_f16acc {};
  511. bool coopmat_support_16x16x16_f32acc {};
  512. bool coopmat1_fa_support {};
  513. uint32_t coopmat_m;
  514. uint32_t coopmat_n;
  515. uint32_t coopmat_k;
  516. bool coopmat_int_support;
  517. uint32_t coopmat_int_m;
  518. uint32_t coopmat_int_n;
  519. uint32_t coopmat_int_k;
  520. bool coopmat2;
  521. bool pipeline_executable_properties_support {};
  522. size_t idx;
  523. bool mul_mat_l[GGML_TYPE_COUNT];
  524. bool mul_mat_m[GGML_TYPE_COUNT];
  525. bool mul_mat_s[GGML_TYPE_COUNT];
  526. bool mul_mat_id_l[GGML_TYPE_COUNT];
  527. bool mul_mat_id_m[GGML_TYPE_COUNT];
  528. bool mul_mat_id_s[GGML_TYPE_COUNT];
  529. vk::DescriptorSetLayout dsl;
  530. vk_matmul_pipeline pipeline_matmul_f32 {};
  531. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  532. vk_matmul_pipeline pipeline_matmul_bf16 {};
  533. vk_matmul_pipeline2 pipeline_matmul_f16;
  534. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  535. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  536. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  537. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  538. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  539. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  540. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  541. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  542. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  543. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  544. vk_pipeline pipeline_matmul_split_k_reduce;
  545. vk_pipeline pipeline_quantize_q8_1_x4;
  546. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  547. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  548. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  549. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  550. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  551. vk_pipeline pipeline_dequant_mul_mat_vec_id_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  552. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  553. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  554. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  555. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  556. vk_pipeline pipeline_acc_f32;
  557. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  558. vk_pipeline pipeline_add[2][2][2];
  559. vk_pipeline pipeline_add_norepeat[2][2][2];
  560. vk_pipeline pipeline_sub[2][2][2];
  561. vk_pipeline pipeline_sub_norepeat[2][2][2];
  562. vk_pipeline pipeline_mul[2][2][2];
  563. vk_pipeline pipeline_mul_norepeat[2][2][2];
  564. vk_pipeline pipeline_div[2][2][2];
  565. vk_pipeline pipeline_div_norepeat[2][2][2];
  566. vk_pipeline pipeline_add_rms[2][2][2];
  567. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  568. // indexed by num_additional_fused_ops == num_adds - 1
  569. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  570. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  571. vk_pipeline pipeline_add_id_f32;
  572. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  573. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32, pipeline_upscale_bilinear_antialias_f32;
  574. vk_pipeline pipeline_scale_f32;
  575. vk_pipeline pipeline_sqr_f32;
  576. vk_pipeline pipeline_sqrt_f32;
  577. vk_pipeline pipeline_sin_f32;
  578. vk_pipeline pipeline_cos_f32;
  579. vk_pipeline pipeline_log[2];
  580. vk_pipeline pipeline_tri[2];
  581. vk_pipeline pipeline_diag[2];
  582. vk_pipeline pipeline_clamp_f32;
  583. vk_pipeline pipeline_pad_f32;
  584. vk_pipeline pipeline_roll_f32;
  585. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  586. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
  587. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
  588. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  589. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  590. vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
  591. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  592. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  593. vk_pipeline pipeline_norm_f32;
  594. vk_pipeline pipeline_group_norm_f32;
  595. vk_pipeline pipeline_rms_norm_f32;
  596. vk_pipeline pipeline_rms_norm_mul_f32;
  597. vk_pipeline pipeline_rms_norm_partials_f32;
  598. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  599. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  600. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  601. vk_pipeline pipeline_rms_norm_back_f32;
  602. vk_pipeline pipeline_l2_norm_f32;
  603. // [src/dst 0=fp32,1=fp16]
  604. vk_pipeline pipeline_exp[2];
  605. vk_pipeline pipeline_gelu[2];
  606. vk_pipeline pipeline_gelu_erf[2];
  607. vk_pipeline pipeline_gelu_quick[2];
  608. vk_pipeline pipeline_silu[2];
  609. vk_pipeline pipeline_relu[2];
  610. vk_pipeline pipeline_xielu[2];
  611. vk_pipeline pipeline_neg[2];
  612. vk_pipeline pipeline_tanh[2];
  613. vk_pipeline pipeline_sigmoid[2];
  614. vk_pipeline pipeline_hardsigmoid[2];
  615. vk_pipeline pipeline_hardswish[2];
  616. vk_pipeline pipeline_abs[2];
  617. vk_pipeline pipeline_softplus[2];
  618. vk_pipeline pipeline_step[2];
  619. vk_pipeline pipeline_round[2];
  620. vk_pipeline pipeline_ceil[2];
  621. vk_pipeline pipeline_floor[2];
  622. vk_pipeline pipeline_trunc[2];
  623. vk_pipeline pipeline_add1_f16_f16;
  624. vk_pipeline pipeline_add1_f16_f32;
  625. vk_pipeline pipeline_add1_f32_f32;
  626. vk_pipeline pipeline_arange_f32;
  627. vk_pipeline pipeline_fill_f32;
  628. vk_pipeline pipeline_geglu[2];
  629. vk_pipeline pipeline_reglu[2];
  630. vk_pipeline pipeline_swiglu[2];
  631. vk_pipeline pipeline_swiglu_oai[2];
  632. vk_pipeline pipeline_geglu_erf[2];
  633. vk_pipeline pipeline_geglu_quick[2];
  634. vk_pipeline pipeline_leaky_relu_f32;
  635. vk_pipeline pipeline_silu_back_f32;
  636. vk_pipeline pipeline_diag_mask_inf_f32;
  637. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  638. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  639. vk_pipeline pipeline_soft_max_back_f32;
  640. vk_pipeline pipeline_soft_max_large1_f32, pipeline_soft_max_large1_f32_f16;
  641. vk_pipeline pipeline_soft_max_large2_f32, pipeline_soft_max_large2_f32_f16;
  642. vk_pipeline pipeline_soft_max_large3_f32, pipeline_soft_max_large3_f32_f16;
  643. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  644. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  645. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16, pipeline_rope_multi_f32_f16;
  646. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  647. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  648. vk_pipeline pipeline_argsort_large_f32[num_argsort_pipelines];
  649. vk_pipeline pipeline_topk_f32[num_topk_pipelines];
  650. vk_pipeline pipeline_sum_rows_f32;
  651. vk_pipeline pipeline_cumsum_f32;
  652. vk_pipeline pipeline_cumsum_small_f32;
  653. vk_pipeline pipeline_cumsum_multipass1_f32;
  654. vk_pipeline pipeline_cumsum_multipass2_f32;
  655. vk_pipeline pipeline_argmax_f32;
  656. vk_pipeline pipeline_count_equal_i32;
  657. std::map<vk_solve_tri_pipeline_state, vk_pipeline> pipeline_solve_tri_f32;
  658. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  659. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  660. vk_pipeline pipeline_timestep_embedding_f32;
  661. vk_pipeline pipeline_conv_transpose_1d_f32;
  662. vk_pipeline pipeline_pool2d_f32;
  663. vk_pipeline pipeline_rwkv_wkv6_f32;
  664. vk_pipeline pipeline_rwkv_wkv7_f32;
  665. vk_pipeline pipeline_ssm_scan_f32_d128;
  666. vk_pipeline pipeline_ssm_scan_f32_d256;
  667. vk_pipeline pipeline_ssm_conv_f32;
  668. vk_pipeline pipeline_opt_step_adamw_f32;
  669. vk_pipeline pipeline_opt_step_sgd_f32;
  670. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  671. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  672. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  673. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  674. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  675. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  676. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  677. vk_pipeline pipeline_flash_attn_split_k_reduce;
  678. vk_pipeline pipeline_count_experts;
  679. // [2] is for whether to take n_experts from spec constant (0) or push constant (1)
  680. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][2];
  681. std::vector<vk_pipeline_ref> all_pipelines;
  682. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  683. vk::Fence fence;
  684. vk_buffer sync_staging;
  685. ggml_backend_buffer_type buffer_type;
  686. bool disable_fusion;
  687. bool disable_host_visible_vidmem;
  688. bool allow_sysmem_fallback;
  689. bool disable_graph_optimize;
  690. #ifdef GGML_VULKAN_MEMORY_DEBUG
  691. std::unique_ptr<vk_memory_logger> memory_logger;
  692. #endif
  693. ~vk_device_struct() {
  694. VK_LOG_DEBUG("destroy device " << name);
  695. device.destroyFence(fence);
  696. ggml_vk_destroy_buffer(sync_staging);
  697. compute_queue.cmd_pool.destroy(device);
  698. transfer_queue.cmd_pool.destroy(device);
  699. for (auto& pipeline : all_pipelines) {
  700. if (pipeline.expired()) {
  701. continue;
  702. }
  703. vk_pipeline pl = pipeline.lock();
  704. ggml_vk_destroy_pipeline(device, pl);
  705. }
  706. all_pipelines.clear();
  707. device.destroyDescriptorSetLayout(dsl);
  708. device.destroy();
  709. }
  710. };
  711. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  712. cmd_buffer_idx = 0;
  713. q = q_;
  714. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  715. pool = device->device.createCommandPool(command_pool_create_info);
  716. }
  717. void vk_command_pool::destroy(vk::Device& device) {
  718. device.destroyCommandPool(pool);
  719. pool = nullptr;
  720. cmd_buffers.clear();
  721. }
  722. struct vk_buffer_struct {
  723. vk::Buffer buffer = VK_NULL_HANDLE;
  724. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  725. vk::MemoryPropertyFlags memory_property_flags;
  726. void * ptr;
  727. size_t size = 0;
  728. vk::DeviceAddress bda_addr {};
  729. vk_device device;
  730. ~vk_buffer_struct() {
  731. if (size == 0) {
  732. return;
  733. }
  734. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  735. device->device.freeMemory(device_memory);
  736. device->device.destroyBuffer(buffer);
  737. }
  738. };
  739. struct vk_subbuffer {
  740. vk_buffer buffer;
  741. uint64_t offset;
  742. uint64_t size;
  743. operator vk::DescriptorBufferInfo() const {
  744. return { buffer->buffer, offset, size };
  745. }
  746. };
  747. // vk_event is used for the event-related backend interfaces. It uses 'event' for
  748. // event_wait and 'fence' for event_synchronize. Polling on an event for
  749. // event_synchronize wouldn't be sufficient to wait for command buffers to complete,
  750. // and would lead to validation errors.
  751. struct vk_event {
  752. vk::Event event;
  753. vk::Fence fence;
  754. };
  755. struct vk_semaphore {
  756. vk::Semaphore s;
  757. uint64_t value;
  758. };
  759. struct vk_submission {
  760. vk::CommandBuffer buffer;
  761. std::vector<vk_semaphore> wait_semaphores;
  762. std::vector<vk_semaphore> signal_semaphores;
  763. };
  764. typedef std::vector<vk_submission> vk_sequence;
  765. struct vk_mat_mat_push_constants {
  766. uint32_t M; uint32_t N; uint32_t K;
  767. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  768. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  769. uint32_t k_split;
  770. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  771. uint32_t padded_N;
  772. };
  773. #define MAT_VEC_FUSION_FLAGS_BIAS0 0x1
  774. #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
  775. #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
  776. #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
  777. struct vk_mat_vec_push_constants {
  778. uint32_t ncols;
  779. uint32_t stride_a;
  780. uint32_t stride_b;
  781. uint32_t stride_d;
  782. uint32_t batch_stride_a;
  783. uint32_t batch_stride_b;
  784. uint32_t batch_stride_d;
  785. uint32_t fusion_flags;
  786. uint32_t ne02;
  787. uint32_t ne12;
  788. uint32_t broadcast2;
  789. uint32_t broadcast3;
  790. };
  791. struct vk_mat_vec_p021_push_constants {
  792. uint32_t ncols_x;
  793. uint32_t nrows_x;
  794. uint32_t nchannels_x;
  795. uint32_t nchannels_y;
  796. uint32_t b_offset;
  797. uint32_t d_offset;
  798. uint32_t fusion_flags;
  799. };
  800. struct vk_mat_vec_nc_push_constants {
  801. uint32_t ncols_x;
  802. uint32_t nrows_x;
  803. uint32_t row_stride_x;
  804. uint32_t channel_stride_x;
  805. uint32_t channel_stride_y;
  806. uint32_t channel_x_divisor;
  807. uint32_t ne12;
  808. uint32_t b_offset;
  809. uint32_t d_offset;
  810. uint32_t nb03;
  811. uint32_t nb13;
  812. uint32_t nb23;
  813. uint32_t fusion_flags;
  814. };
  815. struct vk_mat_mat_id_push_constants {
  816. uint32_t M; uint32_t N; uint32_t K;
  817. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  818. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  819. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  820. uint32_t padded_N;
  821. };
  822. struct vk_mat_vec_id_push_constants {
  823. uint32_t ncols;
  824. uint32_t stride_a;
  825. uint32_t stride_b;
  826. uint32_t stride_d;
  827. uint32_t batch_stride_a;
  828. uint32_t batch_stride_b;
  829. uint32_t batch_stride_d;
  830. uint32_t fusion_flags;
  831. uint32_t nei0;
  832. uint32_t ne11;
  833. };
  834. struct vk_flash_attn_push_constants {
  835. uint32_t N;
  836. uint32_t KV;
  837. uint32_t ne1;
  838. uint32_t ne2;
  839. uint32_t ne3;
  840. uint32_t neq2;
  841. uint32_t neq3;
  842. uint32_t nek2;
  843. uint32_t nek3;
  844. uint32_t nev2;
  845. uint32_t nev3;
  846. uint32_t nem1;
  847. uint32_t nem2;
  848. uint32_t nem3;
  849. uint32_t nb01;
  850. uint32_t nb02;
  851. uint32_t nb03;
  852. uint32_t nb11;
  853. uint32_t nb12;
  854. uint32_t nb13;
  855. uint32_t nb21;
  856. uint32_t nb22;
  857. uint32_t nb23;
  858. float scale;
  859. float max_bias;
  860. float logit_softcap;
  861. uint32_t mask_n_head_log2;
  862. float m0;
  863. float m1;
  864. uint32_t gqa_ratio;
  865. uint32_t split_kv;
  866. uint32_t k_num;
  867. };
  868. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  869. struct vk_op_push_constants {
  870. uint32_t KX;
  871. uint32_t KY;
  872. float param1;
  873. float param2;
  874. float param3;
  875. float param4;
  876. };
  877. struct vk_op_count_experts_push_constants {
  878. uint32_t ne00;
  879. uint32_t ne01;
  880. uint32_t nb00;
  881. uint32_t nb01;
  882. uint32_t a_offset;
  883. };
  884. struct vk_op_glu_push_constants {
  885. uint32_t N;
  886. uint32_t ne00;
  887. uint32_t ne20;
  888. uint32_t mode; // 0: default, 1: swapped, 2: split
  889. float alpha; // for swiglu_oai
  890. float limit;
  891. };
  892. struct vk_op_unary_push_constants {
  893. uint32_t ne;
  894. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  895. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  896. uint32_t misalign_offsets;
  897. float param1; float param2;
  898. uint32_t ne0_012mp; uint32_t ne0_012L;
  899. uint32_t ne0_01mp; uint32_t ne0_01L;
  900. uint32_t ne0_0mp; uint32_t ne0_0L;
  901. uint32_t ne1_012mp; uint32_t ne1_012L;
  902. uint32_t ne1_01mp; uint32_t ne1_01L;
  903. uint32_t ne1_0mp; uint32_t ne1_0L;
  904. };
  905. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  906. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  907. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  908. ne = ne != 0 ? ne : ggml_nelements(dst);
  909. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  910. vk_op_unary_push_constants p{};
  911. p.ne = (uint32_t)ne;
  912. size_t src0_tsize = ggml_type_size(src0->type);
  913. p.ne00 = (uint32_t)src0->ne[0];
  914. p.ne01 = (uint32_t)src0->ne[1];
  915. p.ne02 = (uint32_t)src0->ne[2];
  916. p.ne03 = (uint32_t)src0->ne[3];
  917. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  918. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  919. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  920. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  921. size_t dst_tsize = ggml_type_size(dst->type);
  922. p.ne10 = (uint32_t)dst->ne[0];
  923. p.ne11 = (uint32_t)dst->ne[1];
  924. p.ne12 = (uint32_t)dst->ne[2];
  925. p.ne13 = (uint32_t)dst->ne[3];
  926. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  927. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  928. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  929. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  930. return p; // offsets are initialized later in ggml_vk_op
  931. }
  932. struct vk_op_pad_push_constants {
  933. uint32_t ne;
  934. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  935. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  936. uint32_t misalign_offsets;
  937. uint32_t circular;
  938. uint32_t lp0; uint32_t rp0;
  939. uint32_t lp1; uint32_t rp1;
  940. uint32_t lp2; uint32_t rp2;
  941. uint32_t lp3; uint32_t rp3;
  942. };
  943. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  944. int64_t ne = ggml_nelements(dst);
  945. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  946. vk_op_pad_push_constants p{};
  947. p.ne = (uint32_t)ne;
  948. size_t src0_tsize = ggml_type_size(src0->type);
  949. p.ne00 = (uint32_t)src0->ne[0];
  950. p.ne01 = (uint32_t)src0->ne[1];
  951. p.ne02 = (uint32_t)src0->ne[2];
  952. p.ne03 = (uint32_t)src0->ne[3];
  953. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  954. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  955. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  956. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  957. size_t dst_tsize = ggml_type_size(dst->type);
  958. p.ne10 = (uint32_t)dst->ne[0];
  959. p.ne11 = (uint32_t)dst->ne[1];
  960. p.ne12 = (uint32_t)dst->ne[2];
  961. p.ne13 = (uint32_t)dst->ne[3];
  962. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  963. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  964. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  965. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  966. p.lp0 = dst->op_params[0];
  967. p.rp0 = dst->op_params[1];
  968. p.lp1 = dst->op_params[2];
  969. p.rp1 = dst->op_params[3];
  970. p.lp2 = dst->op_params[4];
  971. p.rp2 = dst->op_params[5];
  972. p.lp3 = dst->op_params[6];
  973. p.rp3 = dst->op_params[7];
  974. p.circular = dst->op_params[8];
  975. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  976. }
  977. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  978. // Precompute mp (m' in the paper) and L such that division
  979. // can be computed using a multiply (high 32b of 64b result)
  980. // and a shift:
  981. //
  982. // n/d = (mulhi(n, mp) + n) >> L;
  983. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  984. {
  985. // compute L = ceil(log2(d));
  986. L = 0;
  987. while (L < 32 && (uint32_t{1} << L) < d) {
  988. L++;
  989. }
  990. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  991. }
  992. template <typename T> void init_pushconst_fastdiv(T &p) {
  993. GGML_UNUSED(p);
  994. static_assert(!std::is_const<T>::value, "unexpected type");
  995. }
  996. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  997. // Compute magic values to divide by these six numbers.
  998. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  999. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  1000. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  1001. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  1002. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  1003. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  1004. }
  1005. struct vk_op_binary_push_constants {
  1006. uint32_t ne;
  1007. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1008. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  1009. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  1010. uint32_t misalign_offsets;
  1011. float param1; float param2; int32_t param3;
  1012. };
  1013. struct vk_op_multi_add_push_constants {
  1014. // shape for dst
  1015. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  1016. // strides for srcs+dst
  1017. uint32_t nb[MAX_PARAMETER_COUNT][4];
  1018. uint32_t rms_partials;
  1019. };
  1020. // update multi_add.comp if this changes
  1021. static_assert(MAX_PARAMETER_COUNT == 12);
  1022. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  1023. struct vk_op_topk_moe_push_constants {
  1024. uint32_t n_rows;
  1025. uint32_t n_experts_push;
  1026. uint32_t n_expert_used;
  1027. float clamp_min;
  1028. float clamp_max;
  1029. uint32_t gating_func;
  1030. uint32_t has_bias;
  1031. uint32_t with_norm;
  1032. float output_scale;
  1033. float output_bias;
  1034. };
  1035. struct vk_op_add_id_push_constants {
  1036. uint32_t ne0;
  1037. uint32_t ne1;
  1038. uint32_t s01;
  1039. uint32_t s02;
  1040. uint32_t s11;
  1041. uint32_t s21;
  1042. };
  1043. struct vk_op_diag_mask_push_constants {
  1044. uint32_t ncols;
  1045. uint32_t rows_per_channel;
  1046. int32_t n_past;
  1047. };
  1048. struct vk_op_rope_push_constants {
  1049. uint32_t rope_mode;
  1050. uint32_t ncols;
  1051. uint32_t nrows;
  1052. uint32_t n_dims;
  1053. float freq_scale;
  1054. uint32_t p_delta_rows;
  1055. float freq_base;
  1056. float ext_factor;
  1057. float attn_factor;
  1058. float corr_dims[2];
  1059. float theta_scale;
  1060. uint32_t has_ff;
  1061. uint32_t ne02;
  1062. uint32_t s1;
  1063. uint32_t s2;
  1064. int32_t sections[4];
  1065. uint32_t is_imrope;
  1066. uint32_t is_back;
  1067. uint32_t set_rows_stride;
  1068. };
  1069. // For fused rms_norm+mul+rope(+view+set_rows)
  1070. struct vk_op_rms_norm_mul_rope_push_constants {
  1071. vk_op_binary_push_constants bin;
  1072. vk_op_rope_push_constants rope;
  1073. };
  1074. struct vk_op_soft_max_push_constants {
  1075. uint32_t KX;
  1076. uint32_t KY;
  1077. uint32_t ne00;
  1078. uint32_t ne01;
  1079. uint32_t ne02;
  1080. uint32_t ne12;
  1081. uint32_t ne13;
  1082. uint32_t nb11;
  1083. uint32_t nb12;
  1084. uint32_t nb13;
  1085. float scale;
  1086. float max_bias;
  1087. float m0;
  1088. float m1;
  1089. uint32_t n_head_log2;
  1090. uint32_t nrows_x;
  1091. uint32_t has_sinks;
  1092. };
  1093. struct vk_op_argsort_push_constants {
  1094. uint32_t ncols;
  1095. uint32_t ncols_padded;
  1096. uint32_t ncols_padded_log2;
  1097. uint32_t nrows;
  1098. uint32_t order;
  1099. uint32_t outer_start;
  1100. uint32_t outer_end;
  1101. uint32_t inner_start;
  1102. uint32_t inner_end;
  1103. };
  1104. struct vk_op_topk_push_constants {
  1105. uint32_t orig_ncols;
  1106. uint32_t ncols_input;
  1107. uint32_t ncols_output;
  1108. uint32_t k;
  1109. uint32_t nrows;
  1110. uint32_t first_pass;
  1111. uint32_t last_pass;
  1112. };
  1113. struct vk_op_im2col_push_constants {
  1114. uint64_t dst_addr;
  1115. uint32_t batch_offset; uint32_t offset_delta;
  1116. uint32_t IC;
  1117. uint32_t IW; uint32_t IH;
  1118. uint32_t OW; uint32_t OH;
  1119. uint32_t KW; uint32_t KH;
  1120. uint32_t pelements;
  1121. uint32_t CHW;
  1122. int32_t s0; int32_t s1;
  1123. int32_t p0; int32_t p1;
  1124. int32_t d0; int32_t d1;
  1125. uint32_t batch_IC;
  1126. };
  1127. struct vk_op_im2col_3d_push_constants {
  1128. uint64_t dst_addr;
  1129. uint32_t nb10;
  1130. uint32_t nb11;
  1131. uint32_t nb12;
  1132. uint32_t nb13;
  1133. uint32_t s0;
  1134. uint32_t s1;
  1135. uint32_t s2;
  1136. uint32_t p0;
  1137. uint32_t p1;
  1138. uint32_t p2;
  1139. uint32_t d0;
  1140. uint32_t d1;
  1141. uint32_t d2;
  1142. uint32_t IW;
  1143. uint32_t IH;
  1144. uint32_t ID;
  1145. uint32_t IC;
  1146. uint32_t KW;
  1147. uint32_t OH;
  1148. uint32_t KD_KH_KW;
  1149. uint32_t KH_KW;
  1150. uint32_t IC_KD_KH_KW;
  1151. uint32_t N_OD_OH;
  1152. uint32_t OD_OH;
  1153. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1154. uint32_t OH_OW_IC_KD_KH_KW;
  1155. uint32_t OW_IC_KD_KH_KW;
  1156. uint32_t misalign_offsets;
  1157. };
  1158. struct vk_op_timestep_embedding_push_constants {
  1159. uint32_t nb1;
  1160. uint32_t dim;
  1161. uint32_t max_period;
  1162. };
  1163. struct vk_op_conv_transpose_1d_push_constants {
  1164. uint32_t Cout;
  1165. uint32_t Cin;
  1166. uint32_t K;
  1167. uint32_t L;
  1168. uint32_t KL;
  1169. uint32_t nb01;
  1170. uint32_t nb02;
  1171. uint32_t nb11;
  1172. uint32_t nb1;
  1173. int32_t s0;
  1174. };
  1175. struct vk_op_pool2d_push_constants {
  1176. uint32_t IW; uint32_t IH;
  1177. uint32_t OW; uint32_t OH;
  1178. uint32_t OC;
  1179. uint32_t pelements;
  1180. uint32_t op;
  1181. int32_t k0; int32_t k1;
  1182. int32_t s0; int32_t s1;
  1183. int32_t p0; int32_t p1;
  1184. };
  1185. struct vk_op_rwkv_wkv6_push_constants {
  1186. uint32_t B;
  1187. uint32_t T;
  1188. uint32_t C;
  1189. uint32_t H;
  1190. };
  1191. struct vk_op_rwkv_wkv7_push_constants {
  1192. uint32_t B;
  1193. uint32_t T;
  1194. uint32_t C;
  1195. uint32_t H;
  1196. };
  1197. struct vk_op_ssm_scan_push_constants {
  1198. uint32_t nb02, nb03, nb12, nb13;
  1199. uint32_t nb21, nb22, nb31;
  1200. uint32_t nb42, nb43, nb52, nb53;
  1201. uint32_t s_off;
  1202. uint32_t n_head, d_head, n_group, n_tok;
  1203. };
  1204. struct vk_op_ssm_conv_push_constants {
  1205. uint32_t nb01, nb02;
  1206. uint32_t nb11;
  1207. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1208. uint32_t nc, ncs, nr, n_t, n_s;
  1209. };
  1210. struct vk_op_conv2d_push_constants {
  1211. uint32_t Cout;
  1212. uint32_t Cin;
  1213. uint32_t N;
  1214. uint32_t W;
  1215. uint32_t H;
  1216. uint32_t OW;
  1217. uint32_t OH;
  1218. uint32_t nb01;
  1219. uint32_t nb02;
  1220. uint32_t nb03;
  1221. uint32_t nb11;
  1222. uint32_t nb12;
  1223. uint32_t nb13;
  1224. uint32_t nb1;
  1225. uint32_t nb2;
  1226. uint32_t nb3;
  1227. // init_fastdiv_values constants for dividing by OW, OW*OH
  1228. uint32_t OWmp; uint32_t OWL;
  1229. uint32_t OWOHmp; uint32_t OWOHL;
  1230. };
  1231. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1232. // Compute magic values to divide by OW, OW*OH
  1233. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1234. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1235. }
  1236. struct vk_op_conv2d_dw_push_constants {
  1237. uint32_t ne;
  1238. uint32_t batches;
  1239. uint32_t channels;
  1240. uint32_t dst_w;
  1241. uint32_t dst_h;
  1242. uint32_t src_w;
  1243. uint32_t src_h;
  1244. uint32_t knl_w;
  1245. uint32_t knl_h;
  1246. int32_t stride_x;
  1247. int32_t stride_y;
  1248. int32_t pad_x;
  1249. int32_t pad_y;
  1250. int32_t dilation_x;
  1251. int32_t dilation_y;
  1252. };
  1253. struct vk_op_upscale_push_constants {
  1254. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1255. uint32_t ne00; uint32_t ne01;
  1256. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1257. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1258. float sf0; float sf1; float sf2; float sf3;
  1259. float pixel_offset;
  1260. };
  1261. struct vk_op_sum_rows_push_constants
  1262. {
  1263. uint32_t n_cols;
  1264. uint32_t ne01, ne02;
  1265. uint32_t nb01, nb02, nb03;
  1266. uint32_t nb11, nb12, nb13;
  1267. float weight;
  1268. uint32_t misalign_offsets;
  1269. uint32_t ne0_12mp, ne0_12L;
  1270. uint32_t ne0_1mp, ne0_1L;
  1271. };
  1272. static vk_op_sum_rows_push_constants vk_op_sum_rows_push_constants_init(const ggml_tensor * src, const ggml_tensor * dst, int64_t n_cols) {
  1273. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1274. vk_op_sum_rows_push_constants p = {};
  1275. p.n_cols = (uint32_t)n_cols;
  1276. p.ne01 = (uint32_t)src->ne[1];
  1277. p.ne02 = (uint32_t)src->ne[2];
  1278. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1279. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1280. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1281. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1282. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1283. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1284. p.weight = 1.0f;
  1285. return p;
  1286. }
  1287. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1288. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1289. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1290. }
  1291. struct vk_quantize_q8_1_push_constants {
  1292. uint32_t ne;
  1293. uint32_t num_blocks;
  1294. };
  1295. // Allow pre-recording command buffers
  1296. struct vk_staging_memcpy {
  1297. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1298. void * dst;
  1299. const void * src;
  1300. size_t n;
  1301. };
  1302. struct vk_staging_memset {
  1303. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1304. void * dst;
  1305. uint32_t val;
  1306. size_t n;
  1307. };
  1308. struct vk_context_struct {
  1309. vk_submission * s;
  1310. std::vector<vk_sequence> seqs;
  1311. int exit_tensor_idx;
  1312. std::vector<vk_staging_memcpy> in_memcpys;
  1313. std::vector<vk_staging_memcpy> out_memcpys;
  1314. std::vector<vk_staging_memset> memsets;
  1315. vk_command_pool * p {};
  1316. };
  1317. typedef std::shared_ptr<vk_context_struct> vk_context;
  1318. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1319. struct ggml_vk_garbage_collector {
  1320. std::vector<vk_semaphore> tl_semaphores;
  1321. std::vector<vk_semaphore> semaphores;
  1322. std::vector<vk::Event> events;
  1323. std::vector<vk_context> contexts;
  1324. };
  1325. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1326. static void ggml_vk_load_shaders(vk_device& device);
  1327. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1328. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1329. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1330. static std::string format_size(size_t size) {
  1331. const size_t kib = 1024;
  1332. const size_t mib = kib * 1024;
  1333. const size_t gib = mib * 1024;
  1334. std::ostringstream oss;
  1335. oss << std::fixed << std::setprecision(2);
  1336. if (size >= gib) {
  1337. oss << static_cast<double>(size) / gib << " GiB";
  1338. } else if (size >= mib) {
  1339. oss << static_cast<double>(size) / mib << " MiB";
  1340. } else if (size >= kib) {
  1341. oss << static_cast<double>(size) / kib << " KiB";
  1342. } else {
  1343. oss << size << " B";
  1344. }
  1345. return oss.str();
  1346. }
  1347. class vk_memory_logger {
  1348. public:
  1349. vk_memory_logger(): total_device(0), total_host(0) {}
  1350. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1351. void log_deallocation(vk_buffer_ref buf_ref);
  1352. private:
  1353. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1354. size_t total_device;
  1355. size_t total_host;
  1356. };
  1357. #else
  1358. #define VK_LOG_MEMORY(msg) ((void) 0)
  1359. #endif // GGML_VULKAN_MEMORY_DEBUG
  1360. static bool vk_perf_logger_enabled = false;
  1361. static bool vk_perf_logger_concurrent = false;
  1362. static bool vk_enable_sync_logger = false;
  1363. // number of calls between perf logger prints
  1364. static uint32_t vk_perf_logger_frequency = 1;
  1365. class vk_perf_logger {
  1366. public:
  1367. void print_timings(bool force = false) {
  1368. if (timings.empty()) {
  1369. return;
  1370. }
  1371. print_count++;
  1372. if ((print_count % vk_perf_logger_frequency) != 0 && !force) {
  1373. return;
  1374. }
  1375. print_count = 0;
  1376. uint64_t total_all_op_times = 0;
  1377. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1378. for (const auto & t : timings) {
  1379. uint64_t total_op_times = 0;
  1380. for (const auto & time : t.second) {
  1381. total_op_times += time;
  1382. }
  1383. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1384. << " us = " << (total_op_times / 1000.0) << " us";
  1385. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1386. auto it = flops.find(t.first);
  1387. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1388. uint64_t total_op_flops = 0;
  1389. for (const auto & elem : it->second) {
  1390. total_op_flops += elem;
  1391. }
  1392. std::cerr << " ("
  1393. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1394. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1395. << " GFLOPS/s)";
  1396. }
  1397. total_all_op_times += total_op_times;
  1398. std::cerr << std::endl;
  1399. }
  1400. if (timings.size() > 0) {
  1401. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1402. }
  1403. timings.clear();
  1404. flops.clear();
  1405. }
  1406. std::string get_node_fusion_name(const ggml_tensor * node, const char *fusion_name, uint64_t *n_flops) {
  1407. *n_flops = 0;
  1408. std::string fusion_str;
  1409. if (fusion_name) {
  1410. fusion_str = fusion_name + std::string(" ");
  1411. }
  1412. if (node->op == GGML_OP_UNARY) {
  1413. return fusion_str + ggml_unary_op_name(ggml_get_unary_op(node));
  1414. }
  1415. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1416. const uint64_t m = node->ne[0];
  1417. const uint64_t n = node->ne[1];
  1418. const uint64_t k = node->src[1]->ne[0];
  1419. const uint64_t batch = node->ne[2] * node->ne[3];
  1420. std::string name = ggml_op_name(node->op);
  1421. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1422. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1423. name += "_VEC";
  1424. }
  1425. name += " ";
  1426. name += ggml_type_name(node->src[0]->type);
  1427. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1428. if (node->op == GGML_OP_MUL_MAT_ID) {
  1429. name += " n_expert=" + std::to_string(node->src[0]->ne[2]);
  1430. }
  1431. if (batch > 1) {
  1432. name += " batch=" + std::to_string(batch);
  1433. }
  1434. name = fusion_str + name;
  1435. *n_flops = m * n * (k + (k - 1)) * batch;
  1436. return name;
  1437. }
  1438. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1439. std::string name = ggml_op_name(node->op);
  1440. ggml_tensor * knl = node->src[0];
  1441. uint64_t OW = node->ne[0];
  1442. uint64_t OH = node->ne[1];
  1443. uint64_t N = node->ne[3];
  1444. uint64_t Cout = node->ne[2];
  1445. uint64_t KW = knl->ne[0];
  1446. uint64_t KH = knl->ne[1];
  1447. uint64_t Cin = node->src[1]->ne[2];
  1448. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1449. uint64_t size_M = Cout;
  1450. uint64_t size_K = Cin * KW * KH;
  1451. uint64_t size_N = N * OW * OH;
  1452. *n_flops = size_M * size_N * (size_K + (size_K - 1));
  1453. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1454. ", N=N*OW*OH=" + std::to_string(size_N);
  1455. name = fusion_str + name;
  1456. return name;
  1457. }
  1458. if (node->op == GGML_OP_RMS_NORM) {
  1459. std::string name = ggml_op_name(node->op);
  1460. name += "(" + std::to_string(node->ne[0]) + "," + std::to_string(node->ne[1]) + "," + std::to_string(node->ne[2]) + "," + std::to_string(node->ne[3]) + ")";
  1461. name = fusion_str + name;
  1462. return name;
  1463. }
  1464. if (node->op == GGML_OP_FLASH_ATTN_EXT) {
  1465. const ggml_tensor * dst = node;
  1466. const ggml_tensor * q = node->src[0];
  1467. const ggml_tensor * k = node->src[1];
  1468. const ggml_tensor * v = node->src[2];
  1469. const ggml_tensor * m = node->src[3];
  1470. std::stringstream name;
  1471. name << fusion_str;
  1472. name << ggml_op_name(node->op) <<
  1473. " dst(" << dst->ne[0] << "," << dst->ne[1] << "," << dst->ne[2] << "," << dst->ne[3] << "), " <<
  1474. " q(" << q->ne[0] << "," << q->ne[1] << "," << q->ne[2] << "," << q->ne[3] << "), " <<
  1475. " k(" << k->ne[0] << "," << k->ne[1] << "," << k->ne[2] << "," << k->ne[3] << "), " <<
  1476. " v(" << v->ne[0] << "," << v->ne[1] << "," << v->ne[2] << "," << v->ne[3] << "), " <<
  1477. " m(" << (m?m->ne[0]:0) << "," << (m?m->ne[1]:0) << "," << (m?m->ne[2]:0) << "," << (m?m->ne[3]:0) << ")";
  1478. return name.str();
  1479. }
  1480. if (node->op == GGML_OP_TOP_K) {
  1481. std::stringstream name;
  1482. name << fusion_str;
  1483. name << ggml_op_name(node->op) <<
  1484. " K=" << node->ne[0] <<
  1485. " (" << node->src[0]->ne[0] << "," << node->src[0]->ne[1] << "," << node->src[0]->ne[2] << "," << node->src[0]->ne[3] << ")";
  1486. return name.str();
  1487. }
  1488. return fusion_str + ggml_op_name(node->op);
  1489. }
  1490. void log_timing(const ggml_tensor * node, const char *fusion_name, uint64_t time) {
  1491. uint64_t n_flops;
  1492. std::string name = get_node_fusion_name(node, fusion_name, &n_flops);
  1493. if (n_flops) {
  1494. flops[name].push_back(n_flops);
  1495. }
  1496. timings[name].push_back(time);
  1497. }
  1498. void log_timing(const std::vector<ggml_tensor *> &nodes, const std::vector<const char *> &names, uint64_t time) {
  1499. uint64_t total_flops = 0;
  1500. std::string name;
  1501. for (size_t n = 0; n < nodes.size(); ++n) {
  1502. uint64_t n_flops = 0;
  1503. name += get_node_fusion_name(nodes[n], names[n], &n_flops);
  1504. total_flops += n_flops;
  1505. if (n != nodes.size() - 1) {
  1506. name += ", ";
  1507. }
  1508. }
  1509. if (total_flops) {
  1510. flops[name].push_back(total_flops);
  1511. }
  1512. timings[name].push_back(time);
  1513. }
  1514. private:
  1515. std::map<std::string, std::vector<uint64_t>> timings;
  1516. std::map<std::string, std::vector<uint64_t>> flops;
  1517. uint32_t print_count {};
  1518. };
  1519. struct ggml_backend_vk_context {
  1520. std::string name;
  1521. vk_device device;
  1522. size_t semaphore_idx, event_idx;
  1523. ggml_vk_garbage_collector gc;
  1524. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1525. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging;
  1526. vk::Fence fence, almost_ready_fence;
  1527. bool submit_pending {};
  1528. bool almost_ready_fence_pending {};
  1529. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1530. // write partial sums to accumulate the square of the vector components
  1531. bool do_add_rms_partials_offset_calculation;
  1532. bool do_add_rms_partials;
  1533. uint64_t last_total_mul_mat_bytes {};
  1534. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1535. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1536. const ggml_tensor * prealloc_y_last_tensor_used {};
  1537. // Track which nodes have been used since the last sync, and whether they were written to
  1538. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1539. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1540. // Track which prealloc buffers have pending reads that need to be synchronized.
  1541. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1542. // and set to true after the buffer contents are consumed.
  1543. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1544. vk_context_ref compute_ctx;
  1545. vk_context_ref transfer_ctx;
  1546. std::vector<vk_context_ref> tensor_ctxs;
  1547. std::vector<vk::DescriptorPool> descriptor_pools;
  1548. std::vector<vk::DescriptorSet> descriptor_sets;
  1549. uint32_t descriptor_set_idx {};
  1550. uint32_t pipeline_descriptor_set_requirements {};
  1551. vk_command_pool compute_cmd_pool;
  1552. vk_command_pool transfer_cmd_pool;
  1553. // number of additional consecutive nodes that are being fused with the
  1554. // node currently being processed
  1555. int num_additional_fused_ops {};
  1556. // Bitmask of which fused ops need to write an intermediate value to memory.
  1557. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1558. // If there's no fusion, bit 0 is still set.
  1559. int fused_ops_write_mask {};
  1560. topk_moe_mode fused_topk_moe_mode {};
  1561. bool fused_topk_moe_scale {};
  1562. // for GGML_VK_PERF_LOGGER
  1563. std::unique_ptr<vk_perf_logger> perf_logger;
  1564. vk::QueryPool query_pool;
  1565. std::vector<const char *> query_fusion_names;
  1566. std::vector<int> query_fusion_node_count;
  1567. std::vector<ggml_tensor *> query_nodes;
  1568. std::vector<int> query_node_idx;
  1569. int32_t num_queries {};
  1570. int32_t query_idx {};
  1571. };
  1572. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1573. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1574. if (tensor->view_src) {
  1575. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1576. }
  1577. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1578. }
  1579. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  1580. {
  1581. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  1582. }
  1583. 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, const ggml_tensor * src3, ggml_tensor * dst) {
  1584. GGML_UNUSED(p);
  1585. GGML_UNUSED(src0);
  1586. GGML_UNUSED(src1);
  1587. GGML_UNUSED(src2);
  1588. GGML_UNUSED(src3);
  1589. GGML_UNUSED(dst);
  1590. static_assert(!std::is_const<T>::value, "unexpected type");
  1591. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  1592. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  1593. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  1594. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  1595. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  1596. }
  1597. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_p021_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1598. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1599. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1600. p.b_offset = b_offset;
  1601. p.d_offset = d_offset;
  1602. GGML_UNUSED(src0);
  1603. GGML_UNUSED(src2);
  1604. GGML_UNUSED(src3);
  1605. }
  1606. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_nc_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1607. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1608. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1609. p.b_offset = b_offset;
  1610. p.d_offset = d_offset;
  1611. GGML_UNUSED(src0);
  1612. GGML_UNUSED(src2);
  1613. GGML_UNUSED(src3);
  1614. }
  1615. struct ggml_backend_vk_buffer_context {
  1616. vk_device_ref device;
  1617. vk_buffer dev_buffer;
  1618. std::string name;
  1619. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1620. device(device),
  1621. dev_buffer(dev_buffer),
  1622. name(name) {
  1623. }
  1624. ~ggml_backend_vk_buffer_context() {
  1625. ggml_vk_destroy_buffer(dev_buffer);
  1626. }
  1627. };
  1628. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1629. static std::mutex log_mutex;
  1630. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1631. std::lock_guard<std::mutex> guard(log_mutex);
  1632. vk_buffer buf = buf_ref.lock();
  1633. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1634. const std::string type = device ? "device" : "host";
  1635. allocations[buf->buffer] = size;
  1636. total_device += device ? size : 0;
  1637. total_host += device ? 0 : size;
  1638. 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));
  1639. }
  1640. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1641. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1642. return;
  1643. }
  1644. std::lock_guard<std::mutex> guard(log_mutex);
  1645. vk_buffer buf = buf_ref.lock();
  1646. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1647. std::string type = device ? "device" : "host";
  1648. auto it = allocations.find(buf->buffer);
  1649. total_device -= device ? it->second : 0;
  1650. total_host -= device ? 0 : it->second;
  1651. if (it != allocations.end()) {
  1652. 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));
  1653. allocations.erase(it);
  1654. } else {
  1655. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1656. }
  1657. }
  1658. #endif // GGML_VULKAN_MEMORY_DEBUG
  1659. struct vk_instance_t {
  1660. vk::Instance instance;
  1661. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1662. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1663. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1664. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1665. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1666. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1667. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1668. std::vector<size_t> device_indices;
  1669. std::vector<bool> device_supports_membudget;
  1670. vk_device devices[GGML_VK_MAX_DEVICES];
  1671. };
  1672. static bool vk_instance_initialized = false;
  1673. static vk_instance_t vk_instance;
  1674. #ifdef GGML_VULKAN_CHECK_RESULTS
  1675. static size_t vk_skip_checks;
  1676. static size_t vk_output_tensor;
  1677. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1678. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1679. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1680. #endif
  1681. 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);
  1682. static void ggml_backend_vk_free(ggml_backend_t backend);
  1683. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1684. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1685. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1686. return range;
  1687. }
  1688. // Wait for ctx->fence to be signaled.
  1689. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1690. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1691. // during this wait.
  1692. if (ctx->almost_ready_fence_pending) {
  1693. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1694. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1695. ctx->almost_ready_fence_pending = false;
  1696. }
  1697. // Spin (w/pause) waiting for the graph to finish executing.
  1698. vk::Result result;
  1699. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1700. if (result != vk::Result::eNotReady) {
  1701. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1702. exit(1);
  1703. }
  1704. for (uint32_t i = 0; i < 100; ++i) {
  1705. YIELD();
  1706. YIELD();
  1707. YIELD();
  1708. YIELD();
  1709. YIELD();
  1710. YIELD();
  1711. YIELD();
  1712. YIELD();
  1713. YIELD();
  1714. YIELD();
  1715. }
  1716. }
  1717. ctx->device->device.resetFences({ ctx->fence });
  1718. }
  1719. // variables to track number of compiles in progress
  1720. static uint32_t compile_count = 0;
  1721. static std::mutex compile_count_mutex;
  1722. static std::condition_variable compile_count_cond;
  1723. static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, size_t spv_size, const void* spv_data, const std::string entrypoint,
  1724. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1725. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1726. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1727. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1728. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1729. GGML_ASSERT(parameter_count > 0);
  1730. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1731. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1732. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1733. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1734. vk::PushConstantRange pcr(
  1735. vk::ShaderStageFlagBits::eCompute,
  1736. 0,
  1737. pipeline->push_constant_size
  1738. );
  1739. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1740. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1741. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1742. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1743. specialization_entries[i].constantID = i;
  1744. specialization_entries[i].offset = i * sizeof(uint32_t);
  1745. specialization_entries[i].size = sizeof(uint32_t);
  1746. }
  1747. vk::SpecializationInfo specialization_info(
  1748. specialization_entries.size(),
  1749. specialization_entries.data(),
  1750. specialization_constants.size() * sizeof(uint32_t),
  1751. specialization_constants.data()
  1752. );
  1753. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1754. if (device->subgroup_require_full_support && require_full_subgroups) {
  1755. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1756. }
  1757. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1758. pipeline_shader_stage_create_flags,
  1759. vk::ShaderStageFlagBits::eCompute,
  1760. pipeline->shader_module,
  1761. entrypoint.c_str(),
  1762. &specialization_info);
  1763. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1764. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1765. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1766. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1767. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1768. }
  1769. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1770. device->pipeline_executable_properties_support ?
  1771. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1772. vk::PipelineCreateFlags{},
  1773. pipeline_shader_create_info,
  1774. pipeline->layout);
  1775. vk::PipelineRobustnessCreateInfoEXT rci;
  1776. if (device->pipeline_robustness && disable_robustness) {
  1777. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1778. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1779. compute_pipeline_create_info.setPNext(&rci);
  1780. }
  1781. try {
  1782. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1783. } catch (const vk::SystemError& e) {
  1784. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1785. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1786. throw e;
  1787. }
  1788. pipeline->compiled = true;
  1789. if (vk_instance.debug_utils_support) {
  1790. vk::DebugUtilsObjectNameInfoEXT duoni;
  1791. duoni.objectType = vk::ObjectType::ePipeline;
  1792. duoni.pObjectName = pipeline->name.c_str();
  1793. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1794. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1795. }
  1796. if (device->pipeline_executable_properties_support) {
  1797. vk::PipelineExecutableInfoKHR executableInfo;
  1798. executableInfo.pipeline = pipeline->pipeline;
  1799. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1800. for (auto & s : statistics) {
  1801. // "Register Count" is reported by NVIDIA drivers.
  1802. if (strcmp(s.name, "Register Count") == 0) {
  1803. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1804. pipeline->register_count = (uint32_t)s.value.u64;
  1805. }
  1806. }
  1807. }
  1808. device->all_pipelines.push_back(pipeline);
  1809. {
  1810. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1811. assert(compile_count > 0);
  1812. compile_count--;
  1813. }
  1814. compile_count_cond.notify_all();
  1815. }
  1816. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1817. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1818. device.destroyPipelineLayout(pipeline->layout);
  1819. device.destroyShaderModule(pipeline->shader_module);
  1820. device.destroyPipeline(pipeline->pipeline);
  1821. }
  1822. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1823. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1824. ctx->pipeline_descriptor_set_requirements += n;
  1825. if (!pipeline->compiled) {
  1826. pipeline->needed = true;
  1827. ggml_vk_load_shaders(ctx->device);
  1828. }
  1829. ggml_pipeline_allocate_descriptor_sets(ctx);
  1830. }
  1831. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1832. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1833. // Enough descriptors are available
  1834. return;
  1835. }
  1836. vk_device& device = ctx->device;
  1837. // Grow by 50% to avoid frequent allocations
  1838. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1839. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1840. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1841. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1842. while (to_alloc > 0) {
  1843. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1844. to_alloc -= alloc_count;
  1845. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1846. if (pool_idx >= ctx->descriptor_pools.size()) {
  1847. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1848. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1849. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1850. }
  1851. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1852. for (uint32_t i = 0; i < alloc_count; i++) {
  1853. layouts[i] = device->dsl;
  1854. }
  1855. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1856. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1857. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1858. pool_idx++;
  1859. }
  1860. }
  1861. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1862. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1863. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1864. // Reuse command buffer
  1865. return p.cmd_buffers[p.cmd_buffer_idx++];
  1866. }
  1867. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1868. p.pool,
  1869. vk::CommandBufferLevel::ePrimary,
  1870. 1);
  1871. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1872. auto buf = cmd_buffers.front();
  1873. p.cmd_buffers.push_back(buf);
  1874. p.cmd_buffer_idx++;
  1875. return buf;
  1876. }
  1877. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1878. if (ctx->seqs.empty()) {
  1879. if (fence) {
  1880. std::lock_guard<std::mutex> guard(queue_mutex);
  1881. ctx->p->q->queue.submit({}, fence);
  1882. }
  1883. return;
  1884. }
  1885. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1886. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1887. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1888. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1889. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1890. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1891. std::vector<vk::SubmitInfo> submit_infos;
  1892. int idx = -1;
  1893. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1894. size_t reserve = 0;
  1895. for (const auto& sequence : ctx->seqs) {
  1896. reserve += sequence.size();
  1897. }
  1898. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1899. tl_wait_semaphores.reserve(reserve);
  1900. tl_wait_vals.reserve(reserve);
  1901. tl_signal_semaphores.reserve(reserve);
  1902. tl_signal_vals.reserve(reserve);
  1903. tl_submit_infos.reserve(reserve);
  1904. submit_infos.reserve(reserve);
  1905. stage_flags.reserve(reserve);
  1906. for (const auto& sequence : ctx->seqs) {
  1907. for (const auto& submission : sequence) {
  1908. stage_flags.push_back({});
  1909. idx++;
  1910. tl_wait_vals.push_back({});
  1911. tl_wait_semaphores.push_back({});
  1912. tl_signal_vals.push_back({});
  1913. tl_signal_semaphores.push_back({});
  1914. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1915. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1916. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1917. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1918. }
  1919. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1920. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1921. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1922. }
  1923. tl_submit_infos.push_back({
  1924. (uint32_t) submission.wait_semaphores.size(),
  1925. tl_wait_vals[idx].data(),
  1926. (uint32_t) submission.signal_semaphores.size(),
  1927. tl_signal_vals[idx].data(),
  1928. });
  1929. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1930. tl_submit_infos[idx].pNext = nullptr;
  1931. vk::SubmitInfo si{
  1932. (uint32_t) submission.wait_semaphores.size(),
  1933. tl_wait_semaphores[idx].data(),
  1934. stage_flags[idx].data(),
  1935. 1,
  1936. &submission.buffer,
  1937. (uint32_t) submission.signal_semaphores.size(),
  1938. tl_signal_semaphores[idx].data(),
  1939. };
  1940. si.setPNext(&tl_submit_infos[idx]);
  1941. submit_infos.push_back(si);
  1942. }
  1943. }
  1944. std::lock_guard<std::mutex> guard(queue_mutex);
  1945. ctx->p->q->queue.submit(submit_infos, fence);
  1946. ctx->seqs.clear();
  1947. }
  1948. 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) {
  1949. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1950. const uint32_t qfsize = queue_family_props.size();
  1951. // Try with avoid preferences first
  1952. for (uint32_t i = 0; i < qfsize; i++) {
  1953. 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)) {
  1954. return i;
  1955. }
  1956. }
  1957. // Fall back to only required
  1958. for (size_t i = 0; i < qfsize; i++) {
  1959. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1960. return i;
  1961. }
  1962. }
  1963. // Fall back to reusing compute queue
  1964. for (size_t i = 0; i < qfsize; i++) {
  1965. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1966. return i;
  1967. }
  1968. }
  1969. // Fall back to ignoring min_num_queries
  1970. for (size_t i = 0; i < qfsize; i++) {
  1971. if (queue_family_props[i].queueFlags & required) {
  1972. return i;
  1973. }
  1974. }
  1975. // 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.
  1976. // 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.
  1977. if (compute_index >= 0) {
  1978. return compute_index;
  1979. }
  1980. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1981. for(auto &q_family : queue_family_props) {
  1982. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1983. }
  1984. abort();
  1985. }
  1986. 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) {
  1987. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1988. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1989. q.queue_family_index = queue_family_index;
  1990. q.transfer_only = transfer_only;
  1991. q.cmd_pool.init(device, &q);
  1992. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1993. q.stage_flags = stage_flags;
  1994. }
  1995. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1996. vk_context result = std::make_shared<vk_context_struct>();
  1997. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1998. ctx->gc.contexts.emplace_back(result);
  1999. result->p = &p;
  2000. return result;
  2001. }
  2002. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  2003. vk_context result = std::make_shared<vk_context_struct>();
  2004. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  2005. result->p = &p;
  2006. return result;
  2007. }
  2008. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  2009. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  2010. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  2011. vk::SemaphoreCreateInfo ci{};
  2012. ci.setPNext(&tci);
  2013. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  2014. ctx->gc.semaphores.push_back({ semaphore, 0 });
  2015. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  2016. }
  2017. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  2018. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  2019. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  2020. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  2021. vk::SemaphoreCreateInfo ci{};
  2022. ci.setPNext(&tci);
  2023. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  2024. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  2025. }
  2026. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  2027. }
  2028. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  2029. if (ctx->event_idx >= ctx->gc.events.size()) {
  2030. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  2031. }
  2032. return ctx->gc.events[ctx->event_idx++];
  2033. }
  2034. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  2035. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  2036. // Requires command buffers to be done
  2037. device->device.resetCommandPool(p.pool);
  2038. p.cmd_buffer_idx = 0;
  2039. }
  2040. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  2041. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  2042. // Arbitrary frequency to cleanup/reuse command buffers
  2043. static constexpr uint32_t cleanup_frequency = 10;
  2044. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  2045. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  2046. }
  2047. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  2048. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  2049. }
  2050. }
  2051. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  2052. std::vector<uint32_t> indices;
  2053. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  2054. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  2055. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  2056. (flags & memory_type.propertyFlags) == flags &&
  2057. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  2058. indices.push_back(i);
  2059. }
  2060. }
  2061. return indices;
  2062. }
  2063. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list,
  2064. void *import_ptr = nullptr) {
  2065. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags_list.begin()[0]) << ", " << to_string(req_flags_list.begin()[req_flags_list.size()-1]) << ")");
  2066. if (size > device->max_buffer_size) {
  2067. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  2068. }
  2069. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  2070. if (size == 0) {
  2071. buf->size = 0;
  2072. return buf;
  2073. }
  2074. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  2075. vk::MemoryAllocateFlags mem_flags {};
  2076. if (device->buffer_device_address) {
  2077. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  2078. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  2079. }
  2080. vk::BufferCreateInfo buffer_create_info{
  2081. vk::BufferCreateFlags(),
  2082. size,
  2083. usage_flags,
  2084. vk::SharingMode::eExclusive,
  2085. 0,
  2086. nullptr,
  2087. };
  2088. vk::ExternalMemoryBufferCreateInfo external_memory_bci;
  2089. if (import_ptr) {
  2090. external_memory_bci.handleTypes = vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT;
  2091. buffer_create_info.setPNext(&external_memory_bci);
  2092. }
  2093. buf->buffer = device->device.createBuffer(buffer_create_info);
  2094. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  2095. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2096. const vk::MemoryPriorityAllocateInfoEXT mem_priority_info { 1.0f };
  2097. vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  2098. if (device->memory_priority) {
  2099. mem_flags_info.setPNext(&mem_priority_info);
  2100. }
  2101. if (import_ptr) {
  2102. vk::MemoryHostPointerPropertiesEXT host_pointer_props;
  2103. try {
  2104. host_pointer_props = device->device.getMemoryHostPointerPropertiesEXT(vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT, import_ptr);
  2105. } catch (vk::SystemError& e) {
  2106. GGML_LOG_WARN("ggml_vulkan: Failed getMemoryHostPointerPropertiesEXT (%s)\n", e.what());
  2107. device->device.destroyBuffer(buf->buffer);
  2108. return {};
  2109. }
  2110. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2111. uint32_t memory_type_idx;
  2112. vk::MemoryPropertyFlags property_flags = *req_flags_list.begin();
  2113. for (memory_type_idx = 0; memory_type_idx < 32; ++memory_type_idx) {
  2114. if (!(host_pointer_props.memoryTypeBits & (1u << memory_type_idx))) {
  2115. continue;
  2116. }
  2117. if (!(mem_req.memoryTypeBits & (1u << memory_type_idx))) {
  2118. continue;
  2119. }
  2120. vk::MemoryType memory_type = mem_props.memoryTypes[memory_type_idx];
  2121. // check for visible+coherent+cached. Other flags (e.g. devicelocal) are allowed
  2122. if ((memory_type.propertyFlags & property_flags) == property_flags) {
  2123. property_flags = memory_type.propertyFlags;
  2124. break;
  2125. }
  2126. }
  2127. if (memory_type_idx == 32) {
  2128. GGML_LOG_WARN("ggml_vulkan: Memory type for host allocation not found\n");
  2129. device->device.destroyBuffer(buf->buffer);
  2130. return {};
  2131. }
  2132. buf->memory_property_flags = mem_props.memoryTypes[memory_type_idx].propertyFlags;
  2133. try {
  2134. vk::ImportMemoryHostPointerInfoEXT import_info;
  2135. import_info.handleType = vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT;
  2136. import_info.pHostPointer = import_ptr;
  2137. import_info.setPNext(&mem_flags_info);
  2138. buf->device_memory = device->device.allocateMemory({ size, memory_type_idx, &import_info });
  2139. } catch (const vk::SystemError& e) {
  2140. }
  2141. } else {
  2142. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  2143. const auto & req_flags = *it;
  2144. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  2145. if (memory_type_indices.empty()) {
  2146. continue;
  2147. }
  2148. buf->memory_property_flags = req_flags;
  2149. bool done = false;
  2150. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  2151. try {
  2152. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  2153. done = true;
  2154. break;
  2155. } catch (const vk::SystemError& e) {
  2156. // loop and retry
  2157. // during last attempt throw the exception
  2158. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  2159. device->device.destroyBuffer(buf->buffer);
  2160. throw e;
  2161. }
  2162. }
  2163. }
  2164. if (done) {
  2165. break;
  2166. }
  2167. }
  2168. }
  2169. if (!buf->device_memory) {
  2170. device->device.destroyBuffer(buf->buffer);
  2171. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  2172. }
  2173. buf->ptr = nullptr;
  2174. if (import_ptr) {
  2175. buf->ptr = import_ptr;
  2176. } else {
  2177. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2178. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  2179. }
  2180. }
  2181. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  2182. buf->device = device;
  2183. buf->size = size;
  2184. if (device->buffer_device_address) {
  2185. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  2186. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  2187. }
  2188. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2189. device->memory_logger->log_allocation(buf, size);
  2190. #endif
  2191. return buf;
  2192. }
  2193. 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)) {
  2194. try {
  2195. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  2196. } catch (const vk::SystemError& e) {
  2197. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  2198. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2199. throw e;
  2200. }
  2201. }
  2202. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  2203. vk_buffer buf;
  2204. try {
  2205. if (device->prefer_host_memory) {
  2206. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2207. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2208. } else if (device->uma) {
  2209. // Fall back to host memory type
  2210. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2211. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2212. } else if (device->disable_host_visible_vidmem) {
  2213. if (device->allow_sysmem_fallback) {
  2214. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2215. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2216. } else {
  2217. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  2218. }
  2219. } else {
  2220. // use rebar if available, otherwise fallback to device only visible memory
  2221. if (device->allow_sysmem_fallback) {
  2222. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2223. vk::MemoryPropertyFlagBits::eDeviceLocal,
  2224. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2225. } else {
  2226. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2227. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2228. }
  2229. }
  2230. } catch (const vk::SystemError& e) {
  2231. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  2232. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2233. throw e;
  2234. }
  2235. return buf;
  2236. }
  2237. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  2238. if (buf == nullptr) {
  2239. return;
  2240. }
  2241. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2242. if (buf->device != nullptr) {
  2243. buf->device->memory_logger->log_deallocation(buf);
  2244. }
  2245. #endif
  2246. buf.reset();
  2247. }
  2248. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  2249. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  2250. }
  2251. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  2252. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  2253. const bool transfer_queue = subctx->p->q->transfer_only;
  2254. if (ctx) {
  2255. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  2256. }
  2257. subctx->s->buffer.pipelineBarrier(
  2258. subctx->p->q->stage_flags,
  2259. subctx->p->q->stage_flags,
  2260. {},
  2261. { {
  2262. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  2263. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  2264. } },
  2265. {},
  2266. {}
  2267. );
  2268. }
  2269. static void ggml_vk_set_event(vk_context& ctx, vk::Event& event) {
  2270. VK_LOG_DEBUG("ggml_vk_set_event()");
  2271. ctx->s->buffer.setEvent(
  2272. event,
  2273. ctx->p->q->stage_flags
  2274. );
  2275. }
  2276. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  2277. VK_LOG_DEBUG("ggml_vk_wait_events()");
  2278. if (events.empty()) {
  2279. return;
  2280. }
  2281. ctx->s->buffer.waitEvents(
  2282. events,
  2283. ctx->p->q->stage_flags,
  2284. ctx->p->q->stage_flags,
  2285. {},
  2286. {},
  2287. {}
  2288. );
  2289. }
  2290. // number of rows/cols for flash attention shader
  2291. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2292. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2293. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsk, uint32_t hsv, bool small_cache) {
  2294. if (hsv >= 192) {
  2295. return 2;
  2296. } else if ((hsv | hsk) & 8 || small_cache) {
  2297. return 4;
  2298. } else {
  2299. return 8;
  2300. }
  2301. }
  2302. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2303. // 128 threads split into four subgroups, each subgroup does 1/4
  2304. // of the Bc dimension.
  2305. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2306. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2307. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2308. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2309. if (path == FA_COOPMAT2) {
  2310. return flash_attention_num_small_rows;
  2311. } else {
  2312. return scalar_flash_attention_num_small_rows;
  2313. }
  2314. }
  2315. static std::array<uint32_t, 2> fa_rows_cols(FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows, bool small_cache) {
  2316. GGML_UNUSED(clamp);
  2317. if (path == FA_SCALAR) {
  2318. if (small_rows) {
  2319. return {scalar_flash_attention_num_small_rows, 64};
  2320. } else {
  2321. if ((hsv | hsk) & 8) {
  2322. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2323. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2324. return {get_fa_scalar_num_large_rows(hsk, hsv, small_cache), 64};
  2325. } else {
  2326. return {get_fa_scalar_num_large_rows(hsk, hsv, small_cache), 32};
  2327. }
  2328. }
  2329. }
  2330. if (path == FA_COOPMAT1) {
  2331. if (small_rows) {
  2332. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2333. } else {
  2334. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2335. }
  2336. }
  2337. // small rows, large cols
  2338. if (small_rows) {
  2339. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2340. }
  2341. // small cols to reduce register count
  2342. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2343. if (hsk >= 512 || hsv >= 512) {
  2344. return {32, 32};
  2345. } else {
  2346. return {64, 32};
  2347. }
  2348. }
  2349. return {64, 64};
  2350. }
  2351. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows, bool small_cache) {
  2352. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows, small_cache)[1];
  2353. }
  2354. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id, ggml_type src0_type) {
  2355. uint32_t lut_size = 0;
  2356. switch (src0_type) {
  2357. case GGML_TYPE_IQ1_S:
  2358. case GGML_TYPE_IQ1_M:
  2359. lut_size = 2*2048 + 4*2048;
  2360. break;
  2361. case GGML_TYPE_IQ2_XXS:
  2362. lut_size = 8*256;
  2363. break;
  2364. case GGML_TYPE_IQ2_XS:
  2365. lut_size = 8*512;
  2366. break;
  2367. case GGML_TYPE_IQ2_S:
  2368. lut_size = 8*1024;
  2369. break;
  2370. case GGML_TYPE_IQ3_XXS:
  2371. lut_size = 4*256;
  2372. break;
  2373. case GGML_TYPE_IQ3_S:
  2374. lut_size = 4*512;
  2375. break;
  2376. case GGML_TYPE_IQ4_NL:
  2377. case GGML_TYPE_IQ4_XS:
  2378. case GGML_TYPE_MXFP4:
  2379. lut_size = 4*16;
  2380. break;
  2381. default:
  2382. break;
  2383. }
  2384. // Needs to be kept up to date on shader changes
  2385. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2386. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2387. const uint32_t warps = warptile[0] / warptile[10];
  2388. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2389. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2390. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2391. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2392. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2393. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2394. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2395. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2396. return supported;
  2397. }
  2398. struct GpuPipelineConfig {
  2399. // GPU architecture identifier.
  2400. // Example: vk_device_architecture::AMD_GCN
  2401. vk_device_architecture arch;
  2402. // Mapping of pipeline names to their specific subgroup sizes.
  2403. // Example: {"soft_max_f32", 64}
  2404. std::unordered_map<std::string, uint32_t> pipelines;
  2405. // Default subgroup size for this GPU.
  2406. // Defaults to 0 if not explicitly provided.
  2407. uint32_t default_subgroup_size = 0;
  2408. };
  2409. // Pipeline configuration for RDNA1 GPUs.
  2410. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2411. {"soft_max", 64}, {"im2col", 64},
  2412. {"argmax", 64}, {"mul_mat_vec", 64},
  2413. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2414. };
  2415. // Pipeline configuration for RDNA2 GPUs.
  2416. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2417. {"soft_max", 64}, {"im2col", 64},
  2418. };
  2419. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2420. // Define configurations for different GPUs.
  2421. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2422. {
  2423. vk_device_architecture::AMD_RDNA1,
  2424. {
  2425. rdna1_pipelines,
  2426. },
  2427. RDNA_DEFAULT_SUBGROUP_SIZE
  2428. },
  2429. {
  2430. vk_device_architecture::AMD_RDNA2,
  2431. {
  2432. rdna2_pipelines,
  2433. },
  2434. RDNA_DEFAULT_SUBGROUP_SIZE
  2435. },
  2436. };
  2437. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2438. for (const auto &config : gpu_pipeline_configs) {
  2439. if (config.arch == arch) {
  2440. auto pipIt = config.pipelines.find(pipeline_name);
  2441. if (pipIt != config.pipelines.end()) {
  2442. return pipIt->second;
  2443. }
  2444. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2445. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2446. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2447. for (const auto &entry : sorted_pipelines) {
  2448. if (pipeline_name.find(entry.first) != std::string::npos) {
  2449. return entry.second;
  2450. }
  2451. }
  2452. return config.default_subgroup_size;
  2453. }
  2454. }
  2455. return 0; // If no matching configuration is found
  2456. }
  2457. static void ggml_vk_load_shaders(vk_device& device) {
  2458. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2459. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2460. // some shaders have a minimum subgroup size
  2461. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2462. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2463. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2464. const uint32_t mul_mat_subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2465. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2466. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2467. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2468. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2469. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2470. // mulmat
  2471. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2472. l_warptile_id, m_warptile_id, s_warptile_id,
  2473. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2474. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2475. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2476. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2477. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2478. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2479. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2480. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2481. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2482. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2483. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2484. uint32_t l_align, m_align, s_align;
  2485. if (device->coopmat2) {
  2486. // spec constants and tile sizes for non-quant matmul/matmul_id
  2487. l_warptile = { 256, 128, 256, 64, 1 };
  2488. m_warptile = { 256, 128, 128, 64, 0 };
  2489. s_warptile = { 128, 64, 64, 64, 0 };
  2490. l_wg_denoms = {128, 256, 1 };
  2491. m_wg_denoms = {128, 128, 1 };
  2492. s_wg_denoms = { 64, 64, 1 };
  2493. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2494. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2495. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2496. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2497. l_mmq_wg_denoms = { 128, 256, 1 };
  2498. m_mmq_wg_denoms = { 128, 128, 1 };
  2499. s_mmq_wg_denoms = { 32, 64, 1 };
  2500. // spec constants and tile sizes for quant matmul (Qi_K)
  2501. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2502. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2503. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2504. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2505. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2506. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2507. // spec constants and tile sizes for quant matmul_id
  2508. l_warptile_mmqid = { 256, 128, 128, 32, 1, device->subgroup_size };
  2509. m_warptile_mmqid = { 256, 128, 64, 32, 0, device->subgroup_size };
  2510. s_warptile_mmqid = { 256, 128, 64, 32, 0, device->subgroup_size };
  2511. l_mmqid_wg_denoms = { 128, 128, 1 };
  2512. m_mmqid_wg_denoms = { 128, 64, 1 };
  2513. s_mmqid_wg_denoms = { 128, 64, 1 };
  2514. l_align = 128;
  2515. m_align = 64;
  2516. s_align = 32;
  2517. } else {
  2518. // Matrix cores require different warp group sizes
  2519. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2520. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2521. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2522. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2523. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2524. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2525. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2526. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2527. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2528. const uint32_t s_warptile_wm = device->subgroup_size == 8 ? 8 : 32;
  2529. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2530. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2531. s_warptile = { subgroup_size_32, 32, 32, 16, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2532. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2533. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2534. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2535. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2536. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2537. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2538. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, 2, 1, 1, subgroup_size_8 };
  2539. // K-quants use even more registers, mitigate by setting WMITER to 1
  2540. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2541. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2542. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 1, 2, 1, 1, subgroup_size_8 };
  2543. l_warptile_id = { 128, 128, 128, 16, mul_mat_subgroup_size_16 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_16 };
  2544. m_warptile_id = { 128, 64, 64, 16, mul_mat_subgroup_size_16, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_16 };
  2545. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2546. l_warptile_mmqid = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_8 };
  2547. m_warptile_mmqid = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_8 };
  2548. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2549. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2550. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2551. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2552. l_warptile_mmqid_int_k = { 128, 128, 128, 32, mul_mat_subgroup_size_16 * 2, 64, 1, 4, 4, 1, mul_mat_subgroup_size_16 };
  2553. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2554. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2555. // chip specific tuning
  2556. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2557. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2558. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2559. } else if (device->vendor_id == VK_VENDOR_ID_AMD && device->coopmat_support) {
  2560. // This is intentionally using tx_m values, slight performance increase
  2561. l_warptile = { 256, 128, 128, 16, subgroup_size_8, 64, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2562. l_warptile_mmq = l_warptile_mmq_int = { 256, 128, 128, 32, subgroup_size_8, 64, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2563. l_warptile_mmq_int_k = { 256, 128, 128, 32, subgroup_size_16, 64, 1, 4, 2, 1, subgroup_size_16 };
  2564. } else if (device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && device->architecture == INTEL_XE2) {
  2565. // Xe2/Xe3 with coopmat enabled - warptile performance tuning
  2566. l_warptile = { 512, 128, 128, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2567. l_warptile_mmq = { 512, 128, 128, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2568. }
  2569. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2570. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2571. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2572. l_align = 128;
  2573. m_align = 64;
  2574. s_align = 32;
  2575. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2576. ggml_type t = (ggml_type)i;
  2577. // Disable medium and large matrix multiplication if not enough shared memory is available
  2578. // Check mmq warptiles as the largest configuration
  2579. // Throw an error if not enough for any matrix multiplication is available
  2580. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2581. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2582. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2583. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2584. device->mul_mat_m[i] = false;
  2585. device->mul_mat_l[i] = false;
  2586. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2587. device->mul_mat_l[i] = false;
  2588. }
  2589. // Disable mul_mat_id if not enough shared memory is available
  2590. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2591. device->mul_mat_id_s[i] = false;
  2592. device->mul_mat_id_m[i] = false;
  2593. device->mul_mat_id_l[i] = false;
  2594. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2595. device->mul_mat_id_m[i] = false;
  2596. device->mul_mat_id_l[i] = false;
  2597. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2598. device->mul_mat_id_l[i] = false;
  2599. }
  2600. }
  2601. }
  2602. if (!device->pipeline_matmul_f32) {
  2603. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2604. }
  2605. if (!device->pipeline_matmul_f32_f16) {
  2606. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2607. }
  2608. if (!device->pipeline_matmul_id_f32) {
  2609. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2610. }
  2611. if (!device->pipeline_matmul_bf16) {
  2612. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2613. }
  2614. if (!device->pipeline_matmul_id_bf16) {
  2615. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2616. }
  2617. std::vector<std::future<void>> compiles;
  2618. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const char *name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2619. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2620. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2621. if (!require_full_subgroups && required_subgroup_size == 0) {
  2622. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2623. }
  2624. if (!pipeline) {
  2625. pipeline = std::make_shared<vk_pipeline_struct>();
  2626. }
  2627. if (!pipeline->initialized) {
  2628. pipeline->name = name;
  2629. pipeline->parameter_count = parameter_count;
  2630. pipeline->push_constant_size = push_constant_size;
  2631. pipeline->wg_denoms = wg_denoms;
  2632. pipeline->align = align;
  2633. pipeline->initialized = true;
  2634. }
  2635. if (!pipeline->needed || pipeline->compiled) {
  2636. return;
  2637. }
  2638. // TODO: We're no longer benefitting from the async compiles (shaders are
  2639. // compiled individually, as needed) and this complexity can be removed.
  2640. {
  2641. // wait until fewer than N compiles are in progress
  2642. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2643. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2644. while (compile_count >= N) {
  2645. compile_count_cond.wait(guard);
  2646. }
  2647. compile_count++;
  2648. }
  2649. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2650. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2651. };
  2652. auto const &ggml_vk_create_pipeline2 = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2653. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2654. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2655. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2656. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2657. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2658. };
  2659. auto const &fa_wg_denoms = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows, bool small_cache) -> std::array<uint32_t, 3> {
  2660. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows, small_cache)[0], 1, 1};
  2661. };
  2662. auto const &fa_spec_constants = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows, bool small_cache) -> std::vector<uint32_t> {
  2663. // For large number of rows, 128 invocations seems to work best.
  2664. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2665. // can't use 256 for D==80.
  2666. // For scalar, use 128 (arbitrary)
  2667. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2668. const uint32_t D = (hsk|hsv);
  2669. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2670. ? scalar_flash_attention_workgroup_size
  2671. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2672. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows, small_cache);
  2673. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2674. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2675. const uint32_t D_lsb = D ^ (D & (D-1));
  2676. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2677. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2678. };
  2679. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2680. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2681. uint32_t HSK = fa.first.HSK; \
  2682. uint32_t HSV = fa.first.HSV; \
  2683. bool small_rows = fa.first.small_rows; \
  2684. bool small_cache = fa.first.small_cache; \
  2685. FaCodePath path = fa.first.path; \
  2686. bool aligned = fa.first.aligned; \
  2687. bool f32acc = fa.first.f32acc; \
  2688. if (path == FAPATH) { \
  2689. if (aligned) { \
  2690. if (f32acc) { \
  2691. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows,small_cache), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows,small_cache), fa_align(FAPATH,HSK,HSV,TYPE,small_rows,small_cache), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2692. } else { \
  2693. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows,small_cache), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows,small_cache), fa_align(FAPATH,HSK,HSV,TYPE,small_rows,small_cache), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2694. } \
  2695. } else { \
  2696. if (f32acc) { \
  2697. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows,small_cache), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows,small_cache), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2698. } else { \
  2699. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows,small_cache), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows,small_cache), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2700. } \
  2701. } \
  2702. } \
  2703. }
  2704. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2705. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2706. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2707. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2708. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2709. if (device->coopmat1_fa_support) {
  2710. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2711. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2712. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2713. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2714. }
  2715. #endif
  2716. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2717. if (device->coopmat2) {
  2718. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2719. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2720. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2721. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2722. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2723. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2724. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2725. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2726. }
  2727. #endif
  2728. #undef CREATE_FA
  2729. const int mul_mat_id_param_count = 5;
  2730. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2731. if (device->coopmat2) {
  2732. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2733. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2734. 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, true); \
  2735. 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, true); \
  2736. 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, true); \
  2737. 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, true); \
  2738. 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, true); \
  2739. 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, true); \
  2740. // Create 2 variants, {f16,f32} accumulator
  2741. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2742. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2743. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2744. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2745. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2746. if (device->coopmat_bf16_support) {
  2747. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2748. }
  2749. #endif
  2750. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0], matmul_q4_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2751. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1], matmul_q4_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2752. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0], matmul_q5_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2753. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1], matmul_q5_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2754. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0], matmul_q8_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2755. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K], matmul_q2_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2756. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K], matmul_q3_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2757. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K], matmul_q4_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2758. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K], matmul_q5_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2759. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K], matmul_q6_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2760. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_S], matmul_iq1_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2761. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_M], matmul_iq1_m_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2762. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2763. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2764. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_S], matmul_iq2_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2765. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2766. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_S], matmul_iq3_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2767. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2768. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2769. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_MXFP4], matmul_mxfp4_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2770. GGML_ASSERT(device->subgroup_ballot);
  2771. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 5)
  2772. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2773. if (device->coopmat_bf16_support) {
  2774. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 5)
  2775. }
  2776. #endif
  2777. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2778. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2779. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2780. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2781. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2782. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2783. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2784. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2785. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2786. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2787. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2788. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2789. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2790. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2791. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2792. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2793. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2794. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2795. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2796. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2797. #undef CREATE_MM
  2798. #undef CREATE_MM2
  2799. } else
  2800. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2801. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2802. if (device->coopmat_support) {
  2803. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2804. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2805. if (device->mul_mat ## ID ## _l[TYPE]) \
  2806. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, true); \
  2807. if (device->mul_mat ## ID ## _m[TYPE]) \
  2808. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, true); \
  2809. if (device->mul_mat ## ID ## _s[TYPE]) \
  2810. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, true); \
  2811. if (device->mul_mat ## ID ## _l[TYPE]) \
  2812. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, true); \
  2813. if (device->mul_mat ## ID ## _m[TYPE]) \
  2814. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, true); \
  2815. if (device->mul_mat ## ID ## _s[TYPE]) \
  2816. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, true); \
  2817. // Create 2 variants, {f16,f32} accumulator
  2818. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2819. if (device->coopmat_acc_f16_support) { \
  2820. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2821. } \
  2822. if (device->coopmat_acc_f32_support) { \
  2823. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2824. } \
  2825. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2826. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2827. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2828. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2829. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2830. if (device->coopmat_bf16_support) {
  2831. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2832. }
  2833. #endif
  2834. if (device->coopmat_acc_f16_support) {
  2835. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2836. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2837. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2838. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2839. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2840. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2841. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2842. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2843. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2844. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2845. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2846. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2847. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2848. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2849. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2850. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2851. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2852. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2853. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2854. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2855. } else {
  2856. CREATE_MM(GGML_TYPE_Q4_0, 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, );
  2857. CREATE_MM(GGML_TYPE_Q4_1, 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, );
  2858. CREATE_MM(GGML_TYPE_Q5_0, 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, );
  2859. CREATE_MM(GGML_TYPE_Q5_1, 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, );
  2860. CREATE_MM(GGML_TYPE_Q8_0, 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, );
  2861. CREATE_MM(GGML_TYPE_Q2_K, 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, );
  2862. CREATE_MM(GGML_TYPE_Q3_K, 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, );
  2863. CREATE_MM(GGML_TYPE_Q4_K, 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, );
  2864. CREATE_MM(GGML_TYPE_Q5_K, 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, );
  2865. CREATE_MM(GGML_TYPE_Q6_K, 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, );
  2866. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2867. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2868. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2869. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2870. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2871. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2872. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2873. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2874. CREATE_MM(GGML_TYPE_IQ4_NL, 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, );
  2875. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2876. }
  2877. GGML_ASSERT(device->subgroup_ballot);
  2878. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2879. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2880. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2881. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2882. if (device->coopmat_bf16_support) {
  2883. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2884. }
  2885. #endif
  2886. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2887. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2888. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2889. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2890. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2891. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2892. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2893. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2894. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2895. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2896. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2897. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2898. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2899. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2900. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2901. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2902. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2903. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2904. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2905. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2906. #undef CREATE_MM2
  2907. #undef CREATE_MM
  2908. } else
  2909. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2910. if (device->fp16) {
  2911. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2912. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2913. if (device->mul_mat ## ID ## _l[TYPE]) \
  2914. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2915. if (device->mul_mat ## ID ## _m[TYPE]) \
  2916. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2917. if (device->mul_mat ## ID ## _s[TYPE]) \
  2918. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2919. if (device->mul_mat ## ID ## _l[TYPE]) \
  2920. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2921. if (device->mul_mat ## ID ## _m[TYPE]) \
  2922. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2923. if (device->mul_mat ## ID ## _s[TYPE]) \
  2924. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2925. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2926. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2927. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->l, #NAMELC "_l", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2928. } \
  2929. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2930. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->m, #NAMELC "_m", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2931. } \
  2932. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2933. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->s, #NAMELC "_s", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2934. } \
  2935. // Create 2 variants, {f16,f32} accumulator
  2936. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2937. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2938. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2939. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2940. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2941. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2942. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2943. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2944. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2945. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2946. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2947. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2948. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2949. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2950. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2951. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2952. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2953. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2954. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2955. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2956. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2957. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2958. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2959. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2960. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2961. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2962. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2963. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2964. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2965. if (device->integer_dot_product) {
  2966. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0], matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2967. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1], matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2968. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0], matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2969. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1], matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2970. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0], matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2971. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_MXFP4], matmul_mxfp4_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2972. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K], matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2973. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K], matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2974. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K], matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2975. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K], matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2976. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K], matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2977. }
  2978. #endif
  2979. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2980. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  2981. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  2982. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  2983. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  2984. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2985. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2986. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2987. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2988. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2989. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2990. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2991. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2992. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2993. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2994. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2995. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2996. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2997. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2998. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2999. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3000. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3001. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3002. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3003. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3004. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3005. if (device->integer_dot_product) {
  3006. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3007. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3008. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3009. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3010. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3011. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3012. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3013. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3014. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3015. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3016. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3017. }
  3018. #endif
  3019. } else {
  3020. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3021. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3022. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3023. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3024. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3025. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3026. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3027. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3028. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3029. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3030. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3031. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3032. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3033. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3034. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3035. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3036. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3037. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3038. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3039. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3040. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3041. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3042. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3043. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3044. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3045. if (device->integer_dot_product) {
  3046. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3047. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3048. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3049. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3050. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3051. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3052. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3053. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3054. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3055. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3056. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3057. }
  3058. #endif
  3059. }
  3060. #undef CREATE_MM2
  3061. #undef CREATE_MMQ
  3062. #undef CREATE_MM
  3063. } else {
  3064. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  3065. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  3066. if (device->mul_mat ## ID ## _l[TYPE]) \
  3067. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  3068. if (device->mul_mat ## ID ## _m[TYPE]) \
  3069. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  3070. if (device->mul_mat ## ID ## _s[TYPE]) \
  3071. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  3072. if (device->mul_mat ## ID ## _l[TYPE]) \
  3073. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  3074. if (device->mul_mat ## ID ## _m[TYPE]) \
  3075. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  3076. if (device->mul_mat ## ID ## _s[TYPE]) \
  3077. 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, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  3078. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  3079. if (device->mul_mat ## ID ## _l[TYPE]) \
  3080. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC "_l", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  3081. if (device->mul_mat ## ID ## _m[TYPE]) \
  3082. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC "_m", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  3083. if (device->mul_mat ## ID ## _s[TYPE]) \
  3084. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC "_s", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  3085. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3086. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3087. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3088. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3089. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3090. CREATE_MM(GGML_TYPE_Q4_0, 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, , 0);
  3091. CREATE_MM(GGML_TYPE_Q4_1, 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, , 0);
  3092. CREATE_MM(GGML_TYPE_Q5_0, 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, , 0);
  3093. CREATE_MM(GGML_TYPE_Q5_1, 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, , 0);
  3094. CREATE_MM(GGML_TYPE_Q8_0, 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, , 0);
  3095. CREATE_MM(GGML_TYPE_Q2_K, 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, , 0);
  3096. CREATE_MM(GGML_TYPE_Q3_K, 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, , 0);
  3097. CREATE_MM(GGML_TYPE_Q4_K, 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, , 0);
  3098. CREATE_MM(GGML_TYPE_Q5_K, 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, , 0);
  3099. CREATE_MM(GGML_TYPE_Q6_K, 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, , 0);
  3100. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3101. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3102. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3103. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3104. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3105. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3106. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3107. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3108. CREATE_MM(GGML_TYPE_IQ4_NL, 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, , 0);
  3109. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  3110. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3111. if (device->integer_dot_product) {
  3112. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  3113. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  3114. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  3115. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  3116. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  3117. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  3118. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  3119. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  3120. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  3121. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  3122. }
  3123. #endif
  3124. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  3125. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3126. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3127. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3128. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3129. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_subgroup_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3130. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_subgroup_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3131. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_subgroup_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3132. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_subgroup_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3133. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_subgroup_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3134. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_subgroup_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3135. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_subgroup_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3136. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_subgroup_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3137. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_subgroup_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3138. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_subgroup_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3139. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_subgroup_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3140. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_subgroup_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3141. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_subgroup_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3142. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_subgroup_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3143. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_subgroup_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3144. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_subgroup_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3145. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_subgroup_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3146. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_subgroup_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3147. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_subgroup_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3148. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_subgroup_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3149. } else {
  3150. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3151. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3152. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3153. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3154. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3155. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3156. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3157. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3158. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3159. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3160. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3161. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3162. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3163. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3164. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3165. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3166. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3167. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3168. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3169. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3170. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3171. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3172. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3173. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3174. }
  3175. }
  3176. // reusing CREATE_MM from the fp32 path
  3177. if ((device->coopmat2 || device->coopmat_support)
  3178. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3179. && !device->coopmat_bf16_support
  3180. #endif
  3181. ) {
  3182. // use scalar tile sizes
  3183. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  3184. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  3185. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  3186. l_wg_denoms = {128, 128, 1 };
  3187. m_wg_denoms = { 64, 64, 1 };
  3188. s_wg_denoms = { 32, 32, 1 };
  3189. if (device->vendor_id == VK_VENDOR_ID_INTEL && device->architecture == INTEL_XE2) {
  3190. // Xe2/Xe3 - bf16 warptile performance tuning
  3191. l_warptile = { 512, 128, 128, 16, subgroup_size_8, 32, 2, 4, 4, 1, subgroup_size_8 };
  3192. }
  3193. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3194. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3195. }
  3196. #undef CREATE_MM
  3197. // mul mat vec
  3198. // the number of rows computed per shader depends on GPU model and quant
  3199. uint32_t rm_stdq = 1;
  3200. uint32_t rm_kq = 2;
  3201. uint32_t rm_stdq_int = 1;
  3202. uint32_t rm_kq_int = 1;
  3203. auto const &rm_iq_int = [](uint32_t i) { return i == 0 ? 8u : 4u; };
  3204. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3205. if (device->architecture == AMD_GCN) {
  3206. rm_stdq = 2;
  3207. rm_kq = 4;
  3208. rm_stdq_int = 4;
  3209. }
  3210. } else if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3211. rm_stdq = 2;
  3212. rm_stdq_int = 2;
  3213. }
  3214. uint32_t rm_iq = 2 * rm_kq;
  3215. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  3216. // Ensure a subgroup size >= 16 is available
  3217. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  3218. const uint32_t subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control && device->subgroup_min_size <= 16 && device->subgroup_max_size >= 16) ? 16 : device->subgroup_size;
  3219. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  3220. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  3221. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  3222. static constexpr uint32_t mul_mat_vec_num_bindings = 5;
  3223. static constexpr uint32_t mul_mat_vec_id_num_bindings = 6;
  3224. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  3225. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  3226. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  3227. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3228. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3229. SHADER_REDUCTION_MODE_SHMEM;
  3230. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3231. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3232. SHADER_REDUCTION_MODE_SHMEM;
  3233. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  3234. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3235. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3236. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3237. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3238. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3239. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3240. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3241. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3242. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3243. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3244. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3245. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3246. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3247. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3248. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3249. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3250. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3251. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3252. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3253. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3254. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3255. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3256. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", arr_dmmv_mxfp4_f32_f32_len[reduc16], arr_dmmv_mxfp4_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3257. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3258. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3259. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3260. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3261. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3262. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3263. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3264. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3265. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3266. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3267. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3268. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3269. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3270. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3271. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3272. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3273. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3274. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3275. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3276. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3277. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3278. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3279. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", arr_dmmv_mxfp4_f16_f32_len[reduc16], arr_dmmv_mxfp4_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3280. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3281. if (device->integer_dot_product) {
  3282. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3283. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3284. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3285. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3286. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3287. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3288. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3289. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3290. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3291. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3292. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3293. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3294. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3295. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int);
  3296. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int);
  3297. }
  3298. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3299. }
  3300. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", arr_dmmv_id_f32_f32_f32_len[reduc], arr_dmmv_id_f32_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {wg_size_subgroup, 1}, 1, false, use_subgroups, force_subgroup_size);
  3301. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", arr_dmmv_id_f16_f32_f32_len[reduc], arr_dmmv_id_f16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size);
  3302. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", arr_dmmv_id_bf16_f32_f32_len[reduc], arr_dmmv_id_bf16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size);
  3303. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", arr_dmmv_id_q4_0_f32_f32_len[reduc], arr_dmmv_id_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3304. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", arr_dmmv_id_q4_1_f32_f32_len[reduc], arr_dmmv_id_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3305. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", arr_dmmv_id_q5_0_f32_f32_len[reduc], arr_dmmv_id_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3306. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", arr_dmmv_id_q5_1_f32_f32_len[reduc], arr_dmmv_id_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3307. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", arr_dmmv_id_q8_0_f32_f32_len[reduc], arr_dmmv_id_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3308. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", arr_dmmv_id_q2_k_f32_f32_len[reduc16], arr_dmmv_id_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3309. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", arr_dmmv_id_q3_k_f32_f32_len[reduc16], arr_dmmv_id_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3310. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", arr_dmmv_id_q4_k_f32_f32_len[reduc16], arr_dmmv_id_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3311. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", arr_dmmv_id_q5_k_f32_f32_len[reduc16], arr_dmmv_id_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3312. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", arr_dmmv_id_q6_k_f32_f32_len[reduc16], arr_dmmv_id_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3313. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", arr_dmmv_id_iq1_s_f32_f32_len[reduc16], arr_dmmv_id_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3314. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", arr_dmmv_id_iq1_m_f32_f32_len[reduc16], arr_dmmv_id_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3315. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", arr_dmmv_id_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3316. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", arr_dmmv_id_iq2_xs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3317. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", arr_dmmv_id_iq2_s_f32_f32_len[reduc16], arr_dmmv_id_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3318. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", arr_dmmv_id_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3319. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", arr_dmmv_id_iq3_s_f32_f32_len[reduc16], arr_dmmv_id_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3320. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", arr_dmmv_id_iq4_xs_f32_f32_len[reduc16], arr_dmmv_id_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3321. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", arr_dmmv_id_iq4_nl_f32_f32_len[reduc16], arr_dmmv_id_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3322. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", arr_dmmv_id_mxfp4_f32_f32_len[reduc16], arr_dmmv_id_mxfp4_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3323. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3324. if (device->integer_dot_product) {
  3325. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3326. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3327. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_q8_1_f32", arr_dmmv_id_q4_0_q8_1_f32_len[reduc], arr_dmmv_id_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3328. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_q8_1_f32", arr_dmmv_id_q4_1_q8_1_f32_len[reduc], arr_dmmv_id_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3329. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_q8_1_f32", arr_dmmv_id_q5_0_q8_1_f32_len[reduc], arr_dmmv_id_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3330. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_q8_1_f32", arr_dmmv_id_q5_1_q8_1_f32_len[reduc], arr_dmmv_id_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3331. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_q8_1_f32", arr_dmmv_id_q8_0_q8_1_f32_len[reduc], arr_dmmv_id_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3332. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_q8_1_f32", arr_dmmv_id_mxfp4_q8_1_f32_len[reduc], arr_dmmv_id_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3333. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_q8_1_f32", arr_dmmv_id_q2_k_q8_1_f32_len[reduc], arr_dmmv_id_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3334. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_q8_1_f32", arr_dmmv_id_q3_k_q8_1_f32_len[reduc], arr_dmmv_id_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3335. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_q8_1_f32", arr_dmmv_id_q4_k_q8_1_f32_len[reduc], arr_dmmv_id_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3336. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_q8_1_f32", arr_dmmv_id_q5_k_q8_1_f32_len[reduc], arr_dmmv_id_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3337. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_q8_1_f32", arr_dmmv_id_q6_k_q8_1_f32_len[reduc], arr_dmmv_id_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3338. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_q8_1_f32", arr_dmmv_id_iq1_s_q8_1_f32_len[reduc], arr_dmmv_id_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_iq_int(0), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(0)}, 1, true, use_subgroups, subgroup_size_int);
  3339. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_q8_1_f32", arr_dmmv_id_iq1_m_q8_1_f32_len[reduc], arr_dmmv_id_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_iq_int(0), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(0)}, 1, true, use_subgroups, subgroup_size_int);
  3340. }
  3341. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3342. }
  3343. #if !defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3344. GGML_UNUSED(rm_stdq_int);
  3345. GGML_UNUSED(rm_kq_int);
  3346. GGML_UNUSED(rm_iq_int);
  3347. #endif
  3348. // dequant shaders
  3349. 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);
  3350. 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);
  3351. 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);
  3352. 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);
  3353. 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);
  3354. 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);
  3355. 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);
  3356. 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);
  3357. 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);
  3358. 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);
  3359. 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);
  3360. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_S], "dequant_iq1_s", dequant_iq1_s_len, dequant_iq1_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3361. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_M], "dequant_iq1_m", dequant_iq1_m_len, dequant_iq1_m_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3362. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XXS], "dequant_iq2_xxs", dequant_iq2_xxs_len, dequant_iq2_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3363. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XS], "dequant_iq2_xs", dequant_iq2_xs_len, dequant_iq2_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3364. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_S], "dequant_iq2_s", dequant_iq2_s_len, dequant_iq2_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3365. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_XXS], "dequant_iq3_xxs", dequant_iq3_xxs_len, dequant_iq3_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3366. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_S], "dequant_iq3_s", dequant_iq3_s_len, dequant_iq3_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3367. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_XS], "dequant_iq4_xs", dequant_iq4_xs_len, dequant_iq4_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3368. 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);
  3369. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_MXFP4], "dequant_mxfp4", dequant_mxfp4_len, dequant_mxfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3370. // get_rows
  3371. 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);
  3372. 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);
  3373. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_BF16], "get_rows_bf16", get_rows_bf16_len, get_rows_bf16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3374. 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);
  3375. 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);
  3376. 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);
  3377. 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);
  3378. 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);
  3379. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q2_K], "get_rows_q2_k", get_rows_q2_k_len, get_rows_q2_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3380. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q3_K], "get_rows_q3_k", get_rows_q3_k_len, get_rows_q3_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3381. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_K], "get_rows_q4_k", get_rows_q4_k_len, get_rows_q4_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3382. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_K], "get_rows_q5_k", get_rows_q5_k_len, get_rows_q5_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3383. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q6_K], "get_rows_q6_k", get_rows_q6_k_len, get_rows_q6_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3384. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_S], "get_rows_iq1_s", get_rows_iq1_s_len, get_rows_iq1_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3385. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_M], "get_rows_iq1_m", get_rows_iq1_m_len, get_rows_iq1_m_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3386. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs", get_rows_iq2_xxs_len, get_rows_iq2_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3387. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs", get_rows_iq2_xs_len, get_rows_iq2_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3388. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_S], "get_rows_iq2_s", get_rows_iq2_s_len, get_rows_iq2_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3389. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs", get_rows_iq3_xxs_len, get_rows_iq3_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3390. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_S], "get_rows_iq3_s", get_rows_iq3_s_len, get_rows_iq3_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3391. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs", get_rows_iq4_xs_len, get_rows_iq4_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3392. 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);
  3393. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_MXFP4], "get_rows_mxfp4", get_rows_mxfp4_len, get_rows_mxfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3394. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_I32], "get_rows_i32", get_rows_i32_len, get_rows_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3395. 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);
  3396. 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);
  3397. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_BF16], "get_rows_bf16_f32", get_rows_bf16_f32_len, get_rows_bf16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3398. 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);
  3399. 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);
  3400. 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);
  3401. 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);
  3402. 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);
  3403. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q2_K], "get_rows_q2_k_f32", get_rows_q2_k_f32_len, get_rows_q2_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3404. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q3_K], "get_rows_q3_k_f32", get_rows_q3_k_f32_len, get_rows_q3_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3405. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_K], "get_rows_q4_k_f32", get_rows_q4_k_f32_len, get_rows_q4_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3406. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_K], "get_rows_q5_k_f32", get_rows_q5_k_f32_len, get_rows_q5_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3407. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q6_K], "get_rows_q6_k_f32", get_rows_q6_k_f32_len, get_rows_q6_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3408. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_S], "get_rows_iq1_s_f32", get_rows_iq1_s_f32_len, get_rows_iq1_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3409. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_M], "get_rows_iq1_m_f32", get_rows_iq1_m_f32_len, get_rows_iq1_m_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3410. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs_f32", get_rows_iq2_xxs_f32_len, get_rows_iq2_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3411. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs_f32", get_rows_iq2_xs_f32_len, get_rows_iq2_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3412. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_S], "get_rows_iq2_s_f32", get_rows_iq2_s_f32_len, get_rows_iq2_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3413. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs_f32", get_rows_iq3_xxs_f32_len, get_rows_iq3_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3414. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_S], "get_rows_iq3_s_f32", get_rows_iq3_s_f32_len, get_rows_iq3_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3415. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs_f32", get_rows_iq4_xs_f32_len, get_rows_iq4_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3416. 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);
  3417. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_MXFP4], "get_rows_mxfp4_f32", get_rows_mxfp4_f32_len, get_rows_mxfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3418. 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);
  3419. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_split_k_reduce, "fa_split_k_reduce", fa_split_k_reduce_len, fa_split_k_reduce_data, "main", 3, 5 * sizeof(uint32_t), {1, device->subgroup_size, 1}, {device->subgroup_size}, 1, true);
  3420. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3421. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_subgroup_len, quantize_q8_1_x4_subgroup_data, "main", 2, sizeof(vk_quantize_q8_1_push_constants), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3422. } else {
  3423. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_len, quantize_q8_1_x4_data, "main", 2, sizeof(vk_quantize_q8_1_push_constants), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3424. }
  3425. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3426. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3427. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  3428. } else {
  3429. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  3430. }
  3431. }
  3432. 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", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_nc_push_constants), {1, 1, 1}, {}, 1);
  3433. 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);
  3434. 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);
  3435. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  3436. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_f32, "rms_norm_mul_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3437. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_partials_f32, "rms_norm_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  3438. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_partials_f32, "rms_norm_mul_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3439. if (device->float_controls_rte_fp16 &&
  3440. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3441. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_rope_f32_f32, "rms_norm_mul_rope_f32_f32", rms_norm_mul_rope_f32_f32_len, rms_norm_mul_rope_f32_f32_data, "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3442. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_rope_f32_f16, "rms_norm_mul_rope_f32_f16", rms_norm_mul_rope_f32_f16_rte_len, rms_norm_mul_rope_f32_f16_rte_data, "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3443. }
  3444. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_back_f32, "rms_norm_back_f32", rms_norm_back_f32_len, rms_norm_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  3445. ggml_vk_create_pipeline(device, device->pipeline_l2_norm_f32, "l2_norm_f32", l2_norm_f32_len, l2_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  3446. 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);
  3447. 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);
  3448. 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);
  3449. ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f32, "cpy_f16_f32", cpy_f16_f32_len, cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3450. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3451. ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3452. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3453. 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);
  3454. 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);
  3455. 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);
  3456. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f32, "contig_cpy_f16_f32", contig_cpy_f16_f32_len, contig_cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3457. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3458. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3459. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3460. ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_32, "cpy_transpose_32", cpy_transpose_32_len, cpy_transpose_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1);
  3461. ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_16, "cpy_transpose_16", cpy_transpose_16_len, cpy_transpose_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1);
  3462. if (device->float_controls_rte_fp16) {
  3463. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_rte_len, cpy_f32_q4_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3464. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_rte_len, cpy_f32_q4_1_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3465. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_rte_len, cpy_f32_q5_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3466. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_rte_len, cpy_f32_q5_1_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3467. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_rte_len, cpy_f32_q8_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3468. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_rte_len, cpy_f32_iq4_nl_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3469. } else {
  3470. 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), {32, 1, 1}, {}, 1);
  3471. 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), {32, 1, 1}, {}, 1);
  3472. 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), {32, 1, 1}, {}, 1);
  3473. 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), {32, 1, 1}, {}, 1);
  3474. 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), {32, 1, 1}, {}, 1);
  3475. 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), {32, 1, 1}, {}, 1);
  3476. }
  3477. #define SET_ROWS(itype, rte) \
  3478. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F32], "set_rows_f32" #itype, set_rows_f32 ## itype ## rte ## _len, set_rows_f32 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3479. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F16], "set_rows_f16" #itype, set_rows_f16 ## itype ## rte ## _len, set_rows_f16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3480. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_BF16], "set_rows_bf16" #itype, set_rows_bf16 ## itype ## rte ## _len, set_rows_bf16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3481. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_0], "set_rows_q4_0" #itype, set_rows_q4_0 ## itype ## rte ## _len, set_rows_q4_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3482. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_1], "set_rows_q4_1" #itype, set_rows_q4_1 ## itype ## rte ## _len, set_rows_q4_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3483. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_0], "set_rows_q5_0" #itype, set_rows_q5_0 ## itype ## rte ## _len, set_rows_q5_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3484. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_1], "set_rows_q5_1" #itype, set_rows_q5_1 ## itype ## rte ## _len, set_rows_q5_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3485. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q8_0], "set_rows_q8_0" #itype, set_rows_q8_0 ## itype ## rte ## _len, set_rows_q8_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3486. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_IQ4_NL], "set_rows_iq4_nl" #itype, set_rows_iq4_nl ## itype ## rte ## _len, set_rows_iq4_nl ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  3487. if (device->float_controls_rte_fp16) {
  3488. SET_ROWS(_i32, _rte)
  3489. SET_ROWS(_i64, _rte)
  3490. } else {
  3491. SET_ROWS(_i32, )
  3492. SET_ROWS(_i64, )
  3493. }
  3494. #undef SET_ROWS
  3495. 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);
  3496. 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);
  3497. 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);
  3498. 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);
  3499. 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);
  3500. 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);
  3501. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3502. std::string s;
  3503. s += std::string(src0_f16 ? "_f16" : "_f32");
  3504. s += std::string(src1_f16 ? "_f16" : "_f32");
  3505. s += std::string(dst_f16 ? "_f16" : "_f32");
  3506. return s;
  3507. };
  3508. bool rte = device->float_controls_rte_fp16;
  3509. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3510. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3511. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3512. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3513. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3514. CREATE_BINARY(add, , {0}, 4)
  3515. CREATE_BINARY(add, _norepeat, {1}, 4)
  3516. CREATE_BINARY(sub, , {0}, 3)
  3517. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3518. CREATE_BINARY(mul, , {0}, 3)
  3519. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3520. CREATE_BINARY(div, , {0}, 3)
  3521. CREATE_BINARY(div, _norepeat, {1}, 3)
  3522. CREATE_BINARY(add_rms, , {0}, 4)
  3523. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3524. #undef CREATE_BINARY
  3525. if (device->multi_add) {
  3526. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3527. ggml_vk_create_pipeline2(device, device->pipeline_multi_add[i], "multi_add_f32_" + std::to_string(i+1), multi_add_f32_len, multi_add_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  3528. ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms[i], "multi_add_rms_f32_" + std::to_string(i+1), multi_add_rms_f32_len, multi_add_rms_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  3529. }
  3530. }
  3531. ggml_vk_create_pipeline(device, device->pipeline_add_id_f32, "add_id_f32", add_id_f32_len, add_id_f32_data, "main", 4, sizeof(vk_op_add_id_push_constants), {1, 1, 1}, {}, 1);
  3532. 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);
  3533. 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);
  3534. 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);
  3535. 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);
  3536. ggml_vk_create_pipeline(device, device->pipeline_upscale_nearest_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_NEAREST}, 1);
  3537. ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR}, 1);
  3538. ggml_vk_create_pipeline(device, device->pipeline_upscale_bicubic_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BICUBIC}, 1);
  3539. ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_antialias_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS}, 1);
  3540. 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);
  3541. 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);
  3542. ggml_vk_create_pipeline(device, device->pipeline_sqrt_f32, "sqrt_f32", sqrt_f32_len, sqrt_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3543. 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);
  3544. 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);
  3545. if (device->float_controls_rte_fp16) {
  3546. ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32_rte", log_f32_rte_len, log_f32_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3547. ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16_rte", log_f16_rte_len, log_f16_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3548. } else {
  3549. ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32", log_f32_len, log_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3550. ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16", log_f16_len, log_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3551. }
  3552. ggml_vk_create_pipeline(device, device->pipeline_tri[0], "tri_f32", tri_f32_len, tri_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3553. ggml_vk_create_pipeline(device, device->pipeline_tri[1], "tri_f16", tri_f16_len, tri_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3554. ggml_vk_create_pipeline(device, device->pipeline_diag[0], "diag_f32", diag_f32_len, diag_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3555. ggml_vk_create_pipeline(device, device->pipeline_diag[1], "diag_f16", diag_f16_len, diag_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3556. 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);
  3557. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_pad_push_constants), {512, 1, 1}, {}, 1);
  3558. ggml_vk_create_pipeline(device, device->pipeline_roll_f32, "roll_f32", roll_f32_len, roll_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3559. 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);
  3560. ggml_vk_create_pipeline(device, device->pipeline_repeat_back_f32, "repeat_back_f32", repeat_back_f32_len, repeat_back_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3561. #define CREATE_UNARY(name) \
  3562. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3563. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3564. CREATE_UNARY(gelu)
  3565. CREATE_UNARY(gelu_erf)
  3566. CREATE_UNARY(gelu_quick)
  3567. CREATE_UNARY(silu)
  3568. CREATE_UNARY(relu)
  3569. CREATE_UNARY(xielu)
  3570. CREATE_UNARY(neg)
  3571. CREATE_UNARY(tanh)
  3572. CREATE_UNARY(sigmoid)
  3573. CREATE_UNARY(hardsigmoid)
  3574. CREATE_UNARY(hardswish)
  3575. CREATE_UNARY(abs)
  3576. CREATE_UNARY(softplus)
  3577. CREATE_UNARY(step)
  3578. CREATE_UNARY(round)
  3579. CREATE_UNARY(ceil)
  3580. CREATE_UNARY(floor)
  3581. CREATE_UNARY(trunc)
  3582. #undef CREATE_UNARY
  3583. #define CREATE_UNARY_RTE(name) \
  3584. if (device->float_controls_rte_fp16) { \
  3585. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3586. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3587. } else { \
  3588. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3589. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3590. }
  3591. CREATE_UNARY_RTE(exp)
  3592. #undef CREATE_UNARY_RTE
  3593. ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f16, "add1_f16_f16", add1_f16_f16_len, add1_f16_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3594. ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f32, "add1_f16_f32", add1_f16_f32_len, add1_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3595. ggml_vk_create_pipeline(device, device->pipeline_add1_f32_f32, "add1_f32_f32", add1_f32_f32_len, add1_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3596. ggml_vk_create_pipeline(device, device->pipeline_arange_f32, "arange_f32", arange_f32_len, arange_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3597. ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3598. #define CREATE_GLU(name) \
  3599. if (device->float_controls_rte_fp16) { \
  3600. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3601. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3602. } else { \
  3603. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3604. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3605. }
  3606. CREATE_GLU(geglu)
  3607. CREATE_GLU(reglu)
  3608. CREATE_GLU(swiglu)
  3609. CREATE_GLU(swiglu_oai)
  3610. CREATE_GLU(geglu_erf)
  3611. CREATE_GLU(geglu_quick)
  3612. #undef CREATE_GLU
  3613. 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);
  3614. ggml_vk_create_pipeline(device, device->pipeline_silu_back_f32, "silu_back_f32", silu_back_f32_len, silu_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3615. 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);
  3616. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3617. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  3618. 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", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3619. 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", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  3620. ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true);
  3621. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32, "soft_max_large1_f32", soft_max_large1_f32_len, soft_max_large1_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3622. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large2_f32, "soft_max_large2_f32", soft_max_large2_f32_len, soft_max_large2_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3623. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large3_f32, "soft_max_large3_f32", soft_max_large3_f32_len, soft_max_large3_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3624. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32_f16, "soft_max_large1_f32_f16", soft_max_large1_f32_f16_len, soft_max_large1_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3625. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large2_f32_f16, "soft_max_large2_f32_f16", soft_max_large2_f32_f16_len, soft_max_large2_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3626. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large3_f32_f16, "soft_max_large3_f32_f16", soft_max_large3_f32_f16_len, soft_max_large3_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3627. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3628. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3629. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32, "rope_multi_f32", rope_multi_f32_len, rope_multi_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3630. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f32, "rope_vision_f32", rope_vision_f32_len, rope_vision_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3631. if (device->float_controls_rte_fp16) {
  3632. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_rte_len, rope_norm_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3633. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_rte_len, rope_neox_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3634. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_rte_len, rope_multi_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3635. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_rte_len, rope_vision_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3636. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_rte_len, rope_norm_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3637. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_rte_len, rope_neox_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3638. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32_f16, "rope_multi_f32_f16", rope_multi_f32_f16_rte_len, rope_multi_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3639. } else {
  3640. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3641. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3642. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_len, rope_multi_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3643. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_len, rope_vision_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3644. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_len, rope_norm_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3645. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_len, rope_neox_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3646. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32_f16, "rope_multi_f32_f16", rope_multi_f32_f16_len, rope_multi_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3647. }
  3648. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3649. uint32_t BLOCK_SIZE = 1u << std::min(i, device->max_workgroup_size_log2);
  3650. if (i <= device->max_workgroup_size_log2 &&
  3651. 2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3652. const uint32_t NCOLS_PADDED_LOG2 = i;
  3653. ggml_vk_create_pipeline2(device, device->pipeline_argsort_f32[i], "argsort_f32_"+std::to_string(i), argsort_f32_len, argsort_f32_data, "main", 3, sizeof(vk_op_argsort_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, NCOLS_PADDED_LOG2}, 1, true);
  3654. }
  3655. const uint32_t WG_UNROLL_FACTOR = BLOCK_SIZE > 1 ? 2 : 1;
  3656. BLOCK_SIZE /= WG_UNROLL_FACTOR;
  3657. ggml_vk_create_pipeline2(device, device->pipeline_argsort_large_f32[i], "argsort_large_f32_"+std::to_string(i), argsort_large_f32_len, argsort_large_f32_data, "main", 3, sizeof(vk_op_argsort_push_constants), {BLOCK_SIZE * WG_UNROLL_FACTOR, 1, 1}, {BLOCK_SIZE, WG_UNROLL_FACTOR}, 1, true);
  3658. }
  3659. for (uint32_t i = 0; i < num_topk_pipelines; ++i) {
  3660. const uint32_t BLOCK_SIZE = 1u << i;
  3661. const uint32_t NCOLS_PADDED_LOG2 = i;
  3662. if (i <= device->max_workgroup_size_log2) {
  3663. uint32_t nary_shmem = 2 * sizeof(int) * BLOCK_SIZE +
  3664. sizeof(int) * device->subgroup_size +
  3665. 2 * sizeof(int) +
  3666. 2 * (BLOCK_SIZE / device->subgroup_size) * sizeof(int);
  3667. if (device->subgroup_arithmetic && device->subgroup_require_full_support && device->subgroup_shuffle && device->subgroup_ballot &&
  3668. nary_shmem <= device->properties.limits.maxComputeSharedMemorySize) {
  3669. ggml_vk_create_pipeline2(device, device->pipeline_topk_f32[i], "topk_f32_"+std::to_string(i), topk_nary_search_f32_len, topk_nary_search_f32_data, "main", 2, sizeof(vk_op_topk_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, device->subgroup_size, device->subgroup_size_log2}, 1, true, true, device->subgroup_size);
  3670. } else if (2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3671. ggml_vk_create_pipeline2(device, device->pipeline_topk_f32[i], "topk_f32_"+std::to_string(i), topk_argsort_f32_len, topk_argsort_f32_data, "main", 2, sizeof(vk_op_topk_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, NCOLS_PADDED_LOG2}, 1, true);
  3672. }
  3673. }
  3674. }
  3675. ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3676. 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_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3677. const uint32_t cumsum_elem_per_thread = (device->vendor_id == VK_VENDOR_ID_AMD || device->vendor_id == VK_VENDOR_ID_INTEL) ? 2 : 4;
  3678. ggml_vk_create_pipeline(device, device->pipeline_cumsum_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 256, device->subgroup_size, cumsum_elem_per_thread }, 1, true, true, device->subgroup_size);
  3679. ggml_vk_create_pipeline(device, device->pipeline_cumsum_small_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 128, device->subgroup_size, 1 }, 1, true, true, device->subgroup_size);
  3680. ggml_vk_create_pipeline(device, device->pipeline_cumsum_multipass1_f32, "cumsum_multipass1_f32", cumsum_multipass1_f32_len, cumsum_multipass1_f32_data, "main", 3, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3681. ggml_vk_create_pipeline(device, device->pipeline_cumsum_multipass2_f32, "cumsum_multipass2_f32", cumsum_multipass2_f32_len, cumsum_multipass2_f32_data, "main", 3, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3682. ggml_vk_create_pipeline(device, device->pipeline_count_equal_i32, "count_equal_i32", count_equal_i32_len, count_equal_i32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, { device->subgroup_size }, 1);
  3683. ggml_vk_create_pipeline(device, device->pipeline_count_experts, "count_experts", count_experts_len, count_experts_data, "main", 2, sizeof(vk_op_count_experts_push_constants), {1, 1, 1}, {}, 1, true);
  3684. for (auto &s : device->pipeline_solve_tri_f32) {
  3685. const vk_solve_tri_pipeline_state &state = s.first;
  3686. // Max number of rows to load at a time, limited by shared memory
  3687. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((state.N + state.K) * sizeof(float));
  3688. // Need at least K invocations, and prefer a minimum of 128 to spread out loading shared memory
  3689. const uint32_t block_size = std::max(128u, 1u << (uint32_t)ceilf(log2f(float(state.K))));
  3690. ggml_vk_create_pipeline(
  3691. device, s.second, "solve_tri_f32",
  3692. solve_tri_f32_len, solve_tri_f32_data, "main", 3,
  3693. sizeof(vk_op_binary_push_constants), {1, 1, 1}, { 0, state.N, state.K, batch_N, block_size }, 1, true);
  3694. }
  3695. #define IM2COL(bda) \
  3696. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32 ## bda ## _len, im2col_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3697. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32, "im2col_3d_f32", im2col_3d_f32 ## bda ## _len, im2col_3d_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3698. if (device->float_controls_rte_fp16) { \
  3699. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_rte ## bda ## _len, im2col_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3700. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16_rte ## bda ## _len, im2col_3d_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3701. } else { \
  3702. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16 ## bda ## _len, im2col_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3703. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16 ## bda ## _len, im2col_3d_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3704. }
  3705. if (device->shader_int64 && device->buffer_device_address) {
  3706. IM2COL(_bda)
  3707. } else {
  3708. IM2COL()
  3709. }
  3710. 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);
  3711. ggml_vk_create_pipeline(device, device->pipeline_conv_transpose_1d_f32, "conv_transpose_1d_f32", conv_transpose_1d_f32_len, conv_transpose_1d_f32_data, "main", 3, sizeof(vk_op_conv_transpose_1d_push_constants), {1, 1, 1}, {}, 1);
  3712. 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);
  3713. 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);
  3714. ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv7_f32, "rwkv_wkv7_f32", rwkv_wkv7_f32_len, rwkv_wkv7_f32_data, "main", 8, sizeof(vk_op_rwkv_wkv7_push_constants), {1, 1, 1}, {device->subgroup_size}, 1);
  3715. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3716. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size}, 1, true, true);
  3717. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size}, 1, true, true);
  3718. } else {
  3719. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
  3720. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
  3721. }
  3722. ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 3, sizeof(vk_op_ssm_conv_push_constants), {32, 1, 1}, {32}, 1);
  3723. ggml_vk_create_pipeline(device, device->pipeline_opt_step_adamw_f32, "opt_step_adamw_f32", opt_step_adamw_f32_len, opt_step_adamw_f32_data, "main", 5, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3724. ggml_vk_create_pipeline(device, device->pipeline_opt_step_sgd_f32, "opt_step_sgd_f32", opt_step_sgd_f32_len, opt_step_sgd_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3725. // conv2d, conv_transpose_2d
  3726. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3727. uint32_t conv2d_WG_SIZE = 256;
  3728. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3729. uint32_t conv2d_TS_K = (s == CONV_SHAPE_64x32) ? 4 : 8;
  3730. uint32_t conv2d_SHMEM_PAD = 4;
  3731. vk_conv_block_size conv2d_BS = vk_conv_block_sizes[s];
  3732. bool conv2d_UNROLL = true;
  3733. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3734. if (device->coopmat2) {
  3735. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3736. }
  3737. #endif
  3738. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3739. conv2d_SHMEM_PAD = 0;
  3740. conv2d_UNROLL = false;
  3741. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3742. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3743. if (s == CONV_SHAPE_128x128 && device->architecture != vk_device_architecture::AMD_GCN) {
  3744. conv2d_UNROLL = false;
  3745. }
  3746. }
  3747. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3748. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3749. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3750. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3751. device->architecture == vk_device_architecture::AMD_GCN;
  3752. if (device->subgroup_shuffle &&
  3753. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3754. allow_collectives_nv &&
  3755. allow_collectives_amd) {
  3756. use_collectives = 1;
  3757. conv2d_BS.CRS = std::min(
  3758. device->subgroup_size,
  3759. conv2d_BS.CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3760. }
  3761. uint32_t conv2d_shmem_req =
  3762. (conv2d_BS.K * (conv2d_BS.CRS + conv2d_SHMEM_PAD) + conv2d_BS.CRS * (conv2d_BS.NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3763. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3764. conv2d_BS.CRS = 8;
  3765. if (use_collectives) {
  3766. conv2d_BS.CRS = std::min(device->subgroup_size, conv2d_BS.CRS);
  3767. }
  3768. }
  3769. std::array<uint32_t, 3> wg_denoms = { conv2d_BS.K, 1, 1 };
  3770. std::vector<uint32_t> spec_constants = { conv2d_WG_SIZE, conv2d_BS.K, conv2d_BS.CRS, conv2d_BS.NPQ, conv2d_TS_K, use_collectives, conv2d_SHMEM_PAD };
  3771. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3772. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3773. const vk_conv2d_pipeline_state &state = c.first; \
  3774. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3775. spec_constants_cpy.push_back(state.s0); \
  3776. spec_constants_cpy.push_back(state.s1); \
  3777. spec_constants_cpy.push_back(state.p0); \
  3778. spec_constants_cpy.push_back(state.p1); \
  3779. spec_constants_cpy.push_back(state.d0); \
  3780. spec_constants_cpy.push_back(state.d1); \
  3781. spec_constants_cpy.push_back(state.KW); \
  3782. spec_constants_cpy.push_back(state.KH); \
  3783. ggml_vk_create_pipeline( \
  3784. device, c.second, #name #type_suffix, \
  3785. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3786. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3787. }
  3788. #define CREATE_CONVS(spv_suffix) \
  3789. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3790. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3791. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3792. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix)
  3793. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3794. if (device->coopmat2) {
  3795. CREATE_CONVS(_cm2)
  3796. } else
  3797. #endif
  3798. if (conv2d_UNROLL) {
  3799. CREATE_CONVS(_unroll)
  3800. } else {
  3801. CREATE_CONVS( )
  3802. }
  3803. #undef CREATE_CONV
  3804. #undef CREATE_CONVS
  3805. }
  3806. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f32, "conv2d_dw_whcn_f32", conv2d_dw_whcn_f32_len, conv2d_dw_whcn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3807. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f32, "conv2d_dw_cwhn_f32", conv2d_dw_cwhn_f32_len, conv2d_dw_cwhn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3808. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f16_f32, "conv2d_dw_whcn_f16_f32", conv2d_dw_whcn_f16_f32_len, conv2d_dw_whcn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3809. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f16_f32, "conv2d_dw_cwhn_f16_f32", conv2d_dw_cwhn_f16_f32_len, conv2d_dw_cwhn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3810. for (uint32_t use_push = 0; use_push < 2; ++use_push) {
  3811. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3812. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][use_push], "topk_moe_f32_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 4, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, use_push}, 1, true, true, device->subgroup_size);
  3813. }
  3814. }
  3815. for (auto &c : compiles) {
  3816. c.wait();
  3817. }
  3818. }
  3819. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3820. static vk_device ggml_vk_get_device(size_t idx) {
  3821. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3822. if (vk_instance.devices[idx] == nullptr) {
  3823. VK_LOG_DEBUG("Initializing new vk_device");
  3824. vk_device device = std::make_shared<vk_device_struct>();
  3825. vk_instance.devices[idx] = device;
  3826. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3827. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3828. #endif
  3829. size_t dev_num = vk_instance.device_indices[idx];
  3830. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3831. if (dev_num >= physical_devices.size()) {
  3832. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3833. throw std::runtime_error("Device not found");
  3834. }
  3835. device->physical_device = physical_devices[dev_num];
  3836. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3837. device->architecture = get_device_architecture(device->physical_device);
  3838. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3839. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3840. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3841. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3842. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3843. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3844. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3845. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3846. bool fp16_storage = false;
  3847. bool fp16_compute = false;
  3848. bool maintenance4_support = false;
  3849. bool sm_builtins = false;
  3850. bool amd_shader_core_properties2 = false;
  3851. bool pipeline_robustness = false;
  3852. bool coopmat2_support = false;
  3853. bool pipeline_executable_properties_support = false;
  3854. device->coopmat_support = false;
  3855. device->integer_dot_product = false;
  3856. bool bfloat16_support = false;
  3857. for (const auto& properties : ext_props) {
  3858. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3859. maintenance4_support = true;
  3860. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3861. fp16_storage = true;
  3862. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3863. fp16_compute = true;
  3864. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3865. sm_builtins = true;
  3866. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3867. amd_shader_core_properties2 = true;
  3868. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3869. pipeline_robustness = true;
  3870. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3871. device->subgroup_size_control = true;
  3872. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3873. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3874. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3875. device->coopmat_support = true;
  3876. device->coopmat_m = 0;
  3877. device->coopmat_n = 0;
  3878. device->coopmat_k = 0;
  3879. #endif
  3880. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3881. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3882. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3883. coopmat2_support = true;
  3884. #endif
  3885. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3886. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3887. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3888. device->integer_dot_product = true;
  3889. #endif
  3890. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3891. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3892. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3893. bfloat16_support = true;
  3894. #endif
  3895. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3896. pipeline_executable_properties_support = true;
  3897. } else if (strcmp("VK_EXT_memory_priority", properties.extensionName) == 0 &&
  3898. getenv("GGML_VK_ENABLE_MEMORY_PRIORITY")) {
  3899. device->memory_priority = true;
  3900. } else if (strcmp("VK_EXT_external_memory_host", properties.extensionName) == 0) {
  3901. device->external_memory_host = true;
  3902. }
  3903. }
  3904. vk::PhysicalDeviceProperties2 props2;
  3905. vk::PhysicalDeviceMaintenance3Properties props3;
  3906. vk::PhysicalDeviceMaintenance4Properties props4;
  3907. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3908. vk::PhysicalDeviceDriverProperties driver_props;
  3909. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3910. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3911. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3912. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3913. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3914. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3915. vk::PhysicalDeviceExternalMemoryHostPropertiesEXT external_memory_host_props;
  3916. props2.pNext = &props3;
  3917. props3.pNext = &subgroup_props;
  3918. subgroup_props.pNext = &driver_props;
  3919. driver_props.pNext = &vk11_props;
  3920. vk11_props.pNext = &vk12_props;
  3921. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3922. if (maintenance4_support) {
  3923. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3924. last_struct = (VkBaseOutStructure *)&props4;
  3925. }
  3926. if (sm_builtins) {
  3927. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3928. last_struct = (VkBaseOutStructure *)&sm_props;
  3929. }
  3930. if (amd_shader_core_properties2) {
  3931. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3932. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3933. }
  3934. if (device->subgroup_size_control) {
  3935. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3936. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3937. }
  3938. #if defined(VK_NV_cooperative_matrix2)
  3939. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3940. if (coopmat2_support) {
  3941. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3942. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3943. }
  3944. #endif
  3945. if (device->integer_dot_product) {
  3946. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3947. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3948. }
  3949. if (device->external_memory_host) {
  3950. last_struct->pNext = (VkBaseOutStructure *)&external_memory_host_props;
  3951. last_struct = (VkBaseOutStructure *)&external_memory_host_props;
  3952. }
  3953. device->physical_device.getProperties2(&props2);
  3954. device->properties = props2.properties;
  3955. device->vendor_id = device->properties.vendorID;
  3956. device->driver_id = driver_props.driverID;
  3957. if (device->driver_id == vk::DriverId::eMoltenvk) {
  3958. // Disable external_memory_host until https://github.com/KhronosGroup/MoltenVK/pull/2622
  3959. // is available in the Vulkan SDK.
  3960. device->external_memory_host = false;
  3961. }
  3962. // Implementing the async backend interfaces seems broken on older Intel HW,
  3963. // see https://github.com/ggml-org/llama.cpp/issues/17302.
  3964. device->support_async = (device->vendor_id != VK_VENDOR_ID_INTEL ||
  3965. std::string(device->properties.deviceName.data()).find("(DG1)") == std::string::npos) &&
  3966. getenv("GGML_VK_DISABLE_ASYNC") == nullptr;
  3967. if (!device->support_async) {
  3968. GGML_LOG_DEBUG("ggml_vulkan: WARNING: Async execution disabled on certain Intel devices.\n");
  3969. }
  3970. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3971. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3972. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3973. } else if (maintenance4_support) {
  3974. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3975. } else {
  3976. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3977. }
  3978. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3979. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3980. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3981. } else if (maintenance4_support) {
  3982. device->max_buffer_size = props4.maxBufferSize;
  3983. } else {
  3984. device->max_buffer_size = device->max_memory_allocation_size;
  3985. }
  3986. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3987. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3988. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3989. } else {
  3990. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3991. device->suballocation_block_size = 1024*1024*1024;
  3992. }
  3993. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3994. device->subgroup_size = subgroup_props.subgroupSize;
  3995. device->subgroup_size_log2 = uint32_t(log2f(float(device->subgroup_size)));
  3996. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3997. if (sm_builtins) {
  3998. device->shader_core_count = sm_props.shaderSMCount;
  3999. } else if (amd_shader_core_properties2) {
  4000. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  4001. } else {
  4002. device->shader_core_count = 0;
  4003. }
  4004. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  4005. device->subgroup_basic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4006. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBasic);
  4007. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4008. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  4009. #ifdef __APPLE__
  4010. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  4011. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  4012. device->subgroup_arithmetic = false;
  4013. }
  4014. #endif
  4015. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4016. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  4017. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4018. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  4019. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4020. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  4021. device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4022. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote);
  4023. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  4024. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4025. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  4026. device->coopmat_support = false;
  4027. }
  4028. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  4029. device->min_imported_host_pointer_alignment = external_memory_host_props.minImportedHostPointerAlignment;
  4030. device->max_workgroup_size_log2 = uint32_t(log2f(float(device->properties.limits.maxComputeWorkGroupInvocations)));
  4031. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  4032. // Try to find a non-graphics compute queue and transfer-focused queues
  4033. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  4034. 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);
  4035. const float priorities[] = { 1.0f, 1.0f };
  4036. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  4037. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  4038. if (compute_queue_family_index != transfer_queue_family_index) {
  4039. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  4040. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  4041. } else if(!device->single_queue) {
  4042. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  4043. } else {
  4044. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  4045. }
  4046. vk::DeviceCreateInfo device_create_info;
  4047. std::vector<const char *> device_extensions;
  4048. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  4049. VkPhysicalDeviceFeatures2 device_features2;
  4050. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4051. device_features2.pNext = nullptr;
  4052. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  4053. VkPhysicalDeviceVulkan11Features vk11_features;
  4054. vk11_features.pNext = nullptr;
  4055. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4056. device_features2.pNext = &vk11_features;
  4057. VkPhysicalDeviceVulkan12Features vk12_features;
  4058. vk12_features.pNext = nullptr;
  4059. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4060. vk11_features.pNext = &vk12_features;
  4061. last_struct = (VkBaseOutStructure *)&vk12_features;
  4062. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  4063. pl_robustness_features.pNext = nullptr;
  4064. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  4065. pl_robustness_features.pipelineRobustness = VK_FALSE;
  4066. if (pipeline_robustness) {
  4067. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  4068. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  4069. device_extensions.push_back("VK_EXT_pipeline_robustness");
  4070. }
  4071. VkPhysicalDeviceMemoryPriorityFeaturesEXT memory_priority_features;
  4072. memory_priority_features.pNext = nullptr;
  4073. memory_priority_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT;
  4074. memory_priority_features.memoryPriority = VK_FALSE;
  4075. if (device->memory_priority) {
  4076. last_struct->pNext = (VkBaseOutStructure *)&memory_priority_features;
  4077. last_struct = (VkBaseOutStructure *)&memory_priority_features;
  4078. device_extensions.push_back("VK_EXT_memory_priority");
  4079. }
  4080. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  4081. subgroup_size_control_features.pNext = nullptr;
  4082. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  4083. subgroup_size_control_features.computeFullSubgroups = false;
  4084. subgroup_size_control_features.subgroupSizeControl = false;
  4085. if (device->subgroup_size_control) {
  4086. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  4087. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  4088. }
  4089. #if defined(VK_KHR_cooperative_matrix)
  4090. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4091. coopmat_features.pNext = nullptr;
  4092. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4093. coopmat_features.cooperativeMatrix = VK_FALSE;
  4094. if (device->coopmat_support) {
  4095. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4096. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4097. }
  4098. #endif
  4099. #if defined(VK_NV_cooperative_matrix2)
  4100. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  4101. coopmat2_features.pNext = nullptr;
  4102. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  4103. if (coopmat2_support) {
  4104. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  4105. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  4106. device_extensions.push_back("VK_NV_cooperative_matrix2");
  4107. }
  4108. #endif
  4109. #if defined(VK_KHR_shader_bfloat16)
  4110. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4111. bfloat16_features.pNext = nullptr;
  4112. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4113. if (bfloat16_support) {
  4114. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4115. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4116. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4117. }
  4118. #endif
  4119. VkPhysicalDeviceMaintenance4Features maint4_features {};
  4120. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  4121. if (maintenance4_support) {
  4122. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  4123. last_struct = (VkBaseOutStructure *)&maint4_features;
  4124. device_extensions.push_back("VK_KHR_maintenance4");
  4125. }
  4126. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4127. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4128. if (device->integer_dot_product) {
  4129. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4130. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4131. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  4132. }
  4133. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  4134. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  4135. if (pipeline_executable_properties_support) {
  4136. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  4137. last_struct = (VkBaseOutStructure *)&pep_features;
  4138. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  4139. }
  4140. if (device->external_memory_host) {
  4141. device_extensions.push_back("VK_EXT_external_memory_host");
  4142. }
  4143. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  4144. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  4145. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  4146. #if defined(VK_KHR_shader_bfloat16)
  4147. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4148. #else
  4149. device->bf16 = false;
  4150. #endif
  4151. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  4152. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  4153. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  4154. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  4155. device->shader_int64 = device_features2.features.shaderInt64;
  4156. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  4157. device->vulkan_memory_model = vk12_features.vulkanMemoryModel;
  4158. if (device->subgroup_size_control) {
  4159. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  4160. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  4161. device_extensions.push_back("VK_EXT_subgroup_size_control");
  4162. }
  4163. device->subgroup_size_control = device->subgroup_size_control &&
  4164. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  4165. subgroup_size_control_features.subgroupSizeControl;
  4166. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  4167. #if defined(VK_KHR_cooperative_matrix)
  4168. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  4169. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  4170. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  4171. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  4172. device->subgroup_max_size >= 32;
  4173. #endif
  4174. if (coopmat2_support) {
  4175. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4176. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  4177. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  4178. coopmat2_features.cooperativeMatrixReductions &&
  4179. coopmat2_features.cooperativeMatrixConversions &&
  4180. coopmat2_features.cooperativeMatrixPerElementOperations &&
  4181. coopmat2_features.cooperativeMatrixTensorAddressing &&
  4182. coopmat2_features.cooperativeMatrixBlockLoads &&
  4183. vk12_features.bufferDeviceAddress) {
  4184. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  4185. uint32_t count = 0;
  4186. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  4187. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  4188. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  4189. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  4190. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  4191. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  4192. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  4193. flexible_dimensions.resize(count, empty_prop);
  4194. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  4195. bool found_fp16_128 = false,
  4196. found_fp16_256 = false,
  4197. found_fp32_128 = false,
  4198. found_fp32_256 = false;
  4199. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  4200. // with 32x16x16 and 256 with 32x32x16.
  4201. for (auto &prop : flexible_dimensions) {
  4202. if (prop.saturatingAccumulation == VK_FALSE &&
  4203. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  4204. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4205. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4206. if (prop.workgroupInvocations == 128 &&
  4207. prop.MGranularity <= 32 &&
  4208. prop.NGranularity <= 16 &&
  4209. prop.KGranularity <= 16) {
  4210. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4211. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4212. found_fp16_128 = true;
  4213. }
  4214. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4215. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4216. found_fp32_128 = true;
  4217. }
  4218. }
  4219. if (prop.workgroupInvocations == 256 &&
  4220. prop.MGranularity <= 32 &&
  4221. prop.NGranularity <= 32 &&
  4222. prop.KGranularity <= 16) {
  4223. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4224. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4225. found_fp16_256 = true;
  4226. }
  4227. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4228. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4229. found_fp32_256 = true;
  4230. }
  4231. }
  4232. }
  4233. }
  4234. if (found_fp16_128 && found_fp16_256 &&
  4235. found_fp32_128 && found_fp32_256 &&
  4236. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  4237. device->coopmat2 = true;
  4238. }
  4239. }
  4240. #endif
  4241. }
  4242. if (!vk11_features.storageBuffer16BitAccess) {
  4243. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  4244. throw std::runtime_error("Unsupported device");
  4245. }
  4246. device_extensions.push_back("VK_KHR_16bit_storage");
  4247. #ifdef GGML_VULKAN_VALIDATE
  4248. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  4249. #endif
  4250. if (device->fp16) {
  4251. device_extensions.push_back("VK_KHR_shader_float16_int8");
  4252. }
  4253. #if defined(VK_KHR_cooperative_matrix)
  4254. if (device->coopmat_support) {
  4255. // Query supported shapes
  4256. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  4257. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  4258. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  4259. uint32_t cm_props_num;
  4260. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  4261. cm_props.resize(cm_props_num);
  4262. for (auto& prop : cm_props) {
  4263. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  4264. }
  4265. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  4266. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  4267. for (auto& prop : cm_props) {
  4268. 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));
  4269. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  4270. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  4271. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4272. ) {
  4273. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  4274. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  4275. // coopmat sizes not set yet
  4276. if (device->coopmat_m == 0) {
  4277. device->coopmat_acc_f32_support = true;
  4278. device->coopmat_m = prop.MSize;
  4279. device->coopmat_n = prop.NSize;
  4280. device->coopmat_k = prop.KSize;
  4281. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4282. // Only enable if shape is identical
  4283. device->coopmat_acc_f32_support = true;
  4284. }
  4285. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4286. device->coopmat_support_16x16x16_f32acc = true;
  4287. }
  4288. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  4289. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  4290. // coopmat sizes not set yet
  4291. if (device->coopmat_m == 0) {
  4292. device->coopmat_acc_f16_support = true;
  4293. device->coopmat_m = prop.MSize;
  4294. device->coopmat_n = prop.NSize;
  4295. device->coopmat_k = prop.KSize;
  4296. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4297. // Only enable if shape is identical
  4298. device->coopmat_acc_f16_support = true;
  4299. }
  4300. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4301. device->coopmat_support_16x16x16_f16acc = true;
  4302. }
  4303. }
  4304. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  4305. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  4306. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  4307. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  4308. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  4309. device->coopmat_int_m == 0
  4310. ) {
  4311. device->coopmat_int_support = true;
  4312. device->coopmat_int_m = prop.MSize;
  4313. device->coopmat_int_n = prop.NSize;
  4314. device->coopmat_int_k = prop.KSize;
  4315. }
  4316. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4317. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4318. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4319. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4320. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4321. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4322. ) {
  4323. // coopmat sizes not set yet
  4324. if (device->coopmat_m == 0) {
  4325. device->coopmat_bf16_support = true;
  4326. device->coopmat_m = prop.MSize;
  4327. device->coopmat_n = prop.NSize;
  4328. device->coopmat_k = prop.KSize;
  4329. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4330. // Only enable if shape is identical
  4331. device->coopmat_bf16_support = true;
  4332. }
  4333. }
  4334. #endif
  4335. }
  4336. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  4337. // No suitable matmul mode found
  4338. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  4339. device->coopmat_support = false;
  4340. }
  4341. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4342. device->coopmat_bf16_support = false;
  4343. }
  4344. }
  4345. if (device->coopmat_support) {
  4346. device_extensions.push_back("VK_KHR_cooperative_matrix");
  4347. }
  4348. #if defined(VK_KHR_shader_bfloat16)
  4349. if (device->coopmat_bf16_support) {
  4350. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4351. }
  4352. #endif
  4353. #endif
  4354. device->name = GGML_VK_NAME + std::to_string(idx);
  4355. device_create_info = {
  4356. vk::DeviceCreateFlags(),
  4357. device_queue_create_infos,
  4358. {},
  4359. device_extensions
  4360. };
  4361. device_create_info.setPNext(&device_features2);
  4362. device->device = device->physical_device.createDevice(device_create_info);
  4363. // Queues
  4364. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  4365. // Shaders
  4366. // Disable matmul tile sizes early if performance low or not supported
  4367. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  4368. switch (device->vendor_id) {
  4369. #ifndef GGML_VULKAN_RUN_TESTS
  4370. case VK_VENDOR_ID_AMD:
  4371. device->mul_mat_l[i] = device->coopmat_support;
  4372. device->mul_mat_m[i] = true;
  4373. device->mul_mat_s[i] = true;
  4374. device->mul_mat_id_l[i] = false;
  4375. device->mul_mat_id_m[i] = true;
  4376. device->mul_mat_id_s[i] = true;
  4377. break;
  4378. case VK_VENDOR_ID_INTEL:
  4379. if (!device->coopmat_support || device->architecture != INTEL_XE2) {
  4380. device->mul_mat_l[i] = false;
  4381. device->mul_mat_id_l[i] = false;
  4382. } else {
  4383. device->mul_mat_l[i] = true; // if coopmat & XE2+, allow large matmul warptile config for Intel
  4384. device->mul_mat_id_l[i] = true;
  4385. }
  4386. device->mul_mat_m[i] = true;
  4387. device->mul_mat_s[i] = true;
  4388. device->mul_mat_id_m[i] = true;
  4389. device->mul_mat_id_s[i] = true;
  4390. break;
  4391. case VK_VENDOR_ID_APPLE:
  4392. device->mul_mat_l[i] = false;
  4393. device->mul_mat_m[i] = true;
  4394. device->mul_mat_s[i] = false;
  4395. device->mul_mat_id_l[i] = false;
  4396. device->mul_mat_id_m[i] = true;
  4397. device->mul_mat_id_s[i] = false;
  4398. break;
  4399. #endif
  4400. default:
  4401. device->mul_mat_l[i] = true;
  4402. device->mul_mat_m[i] = true;
  4403. device->mul_mat_s[i] = true;
  4404. device->mul_mat_id_l[i] = true;
  4405. device->mul_mat_id_m[i] = true;
  4406. device->mul_mat_id_s[i] = true;
  4407. break;
  4408. }
  4409. }
  4410. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  4411. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  4412. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  4413. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  4414. dsl_binding_flags.push_back({});
  4415. }
  4416. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  4417. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  4418. {},
  4419. dsl_binding);
  4420. descriptor_set_layout_create_info.setPNext(&dslbfci);
  4421. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  4422. ggml_vk_load_shaders(device);
  4423. if (!device->single_queue) {
  4424. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  4425. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  4426. } else {
  4427. // TODO: Use pointer or reference to avoid copy
  4428. device->transfer_queue.copyFrom(device->compute_queue);
  4429. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  4430. }
  4431. device->buffer_type = {
  4432. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4433. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  4434. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  4435. };
  4436. device->fence = device->device.createFence({});
  4437. device->idx = idx;
  4438. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  4439. device->add_rms_fusion = !device->disable_fusion &&
  4440. device->subgroup_arithmetic &&
  4441. device->vendor_id != VK_VENDOR_ID_INTEL;
  4442. device->partials_binding_alignment =
  4443. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  4444. device->mmvq_mode = 0;
  4445. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  4446. device->mmvq_mode = -1;
  4447. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  4448. device->mmvq_mode = 1;
  4449. }
  4450. return device;
  4451. }
  4452. return vk_instance.devices[idx];
  4453. }
  4454. static void ggml_vk_print_gpu_info(size_t idx) {
  4455. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4456. size_t dev_num = vk_instance.device_indices[idx];
  4457. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4458. GGML_ASSERT(vk_instance_initialized);
  4459. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4460. if (dev_num >= devices.size()) {
  4461. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4462. throw std::runtime_error("Device not found");
  4463. }
  4464. vk::PhysicalDevice physical_device = devices[dev_num];
  4465. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4466. bool fp16_storage = false;
  4467. bool fp16_compute = false;
  4468. bool coopmat_support = false;
  4469. bool coopmat2_support = false;
  4470. bool integer_dot_product = false;
  4471. bool bfloat16_support = false;
  4472. for (auto properties : ext_props) {
  4473. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4474. fp16_storage = true;
  4475. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4476. fp16_compute = true;
  4477. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4478. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4479. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4480. coopmat_support = true;
  4481. #endif
  4482. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4483. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4484. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4485. coopmat2_support = true;
  4486. #endif
  4487. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4488. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4489. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4490. integer_dot_product = true;
  4491. #endif
  4492. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4493. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4494. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4495. bfloat16_support = true;
  4496. #endif
  4497. }
  4498. }
  4499. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4500. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4501. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4502. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4503. vk::PhysicalDeviceProperties2 props2;
  4504. vk::PhysicalDeviceMaintenance3Properties props3;
  4505. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4506. vk::PhysicalDeviceDriverProperties driver_props;
  4507. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4508. props2.pNext = &props3;
  4509. props3.pNext = &subgroup_props;
  4510. subgroup_props.pNext = &driver_props;
  4511. // Pointer to the last chain element
  4512. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4513. if (integer_dot_product) {
  4514. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4515. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4516. }
  4517. physical_device.getProperties2(&props2);
  4518. VkPhysicalDeviceFeatures2 device_features2;
  4519. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4520. device_features2.pNext = nullptr;
  4521. VkPhysicalDeviceVulkan11Features vk11_features;
  4522. vk11_features.pNext = nullptr;
  4523. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4524. device_features2.pNext = &vk11_features;
  4525. VkPhysicalDeviceVulkan12Features vk12_features;
  4526. vk12_features.pNext = nullptr;
  4527. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4528. vk11_features.pNext = &vk12_features;
  4529. // Pointer to the last chain element
  4530. last_struct = (VkBaseOutStructure *)&vk12_features;
  4531. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4532. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4533. coopmat_features.pNext = nullptr;
  4534. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4535. coopmat_features.cooperativeMatrix = VK_FALSE;
  4536. if (coopmat_support) {
  4537. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4538. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4539. }
  4540. #endif
  4541. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4542. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4543. if (integer_dot_product) {
  4544. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4545. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4546. }
  4547. #if defined(VK_KHR_shader_bfloat16)
  4548. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4549. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4550. if (bfloat16_support) {
  4551. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4552. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4553. }
  4554. #endif
  4555. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4556. fp16 = fp16 && vk12_features.shaderFloat16;
  4557. #if defined(VK_KHR_shader_bfloat16)
  4558. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4559. #else
  4560. bool bf16 = false;
  4561. #endif
  4562. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4563. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4564. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4565. integer_dot_product = integer_dot_product
  4566. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4567. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4568. coopmat_support = coopmat_support
  4569. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4570. && coopmat_features.cooperativeMatrix
  4571. #endif
  4572. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4573. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4574. std::string device_name = props2.properties.deviceName.data();
  4575. GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %d | bf16: %d | warp size: %zu | shared memory: %d | int dot: %d | matrix cores: %s\n",
  4576. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4577. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4578. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4579. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4580. }
  4581. }
  4582. static bool ggml_vk_instance_layer_settings_available();
  4583. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4584. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4585. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4586. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4587. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4588. return ggml_vk_default_dispatcher_instance;
  4589. }
  4590. static void ggml_vk_instance_init() {
  4591. if (vk_instance_initialized) {
  4592. return;
  4593. }
  4594. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4595. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4596. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4597. uint32_t api_version = vk::enumerateInstanceVersion();
  4598. if (api_version < VK_API_VERSION_1_2) {
  4599. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4600. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4601. }
  4602. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4603. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4604. const bool layer_settings = ggml_vk_instance_layer_settings_available();
  4605. #ifdef __APPLE__
  4606. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4607. #endif
  4608. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4609. std::vector<const char*> layers;
  4610. if (layer_settings) {
  4611. layers.push_back("VK_LAYER_KHRONOS_validation");
  4612. }
  4613. std::vector<const char*> extensions;
  4614. if (layer_settings) {
  4615. extensions.push_back("VK_EXT_layer_settings");
  4616. }
  4617. #ifdef __APPLE__
  4618. if (portability_enumeration_ext) {
  4619. extensions.push_back("VK_KHR_portability_enumeration");
  4620. }
  4621. #endif
  4622. if (debug_utils_ext) {
  4623. extensions.push_back("VK_EXT_debug_utils");
  4624. }
  4625. VkBool32 enable_best_practice = layer_settings;
  4626. std::vector<vk::LayerSettingEXT> settings = {
  4627. {
  4628. "VK_LAYER_KHRONOS_validation",
  4629. "validate_best_practices",
  4630. vk::LayerSettingTypeEXT::eBool32,
  4631. 1,
  4632. &enable_best_practice
  4633. },
  4634. };
  4635. vk::LayerSettingsCreateInfoEXT layer_setting_info(settings);
  4636. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions, &layer_setting_info);
  4637. #ifdef __APPLE__
  4638. if (portability_enumeration_ext) {
  4639. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4640. }
  4641. #endif
  4642. vk_instance.instance = vk::createInstance(instance_create_info);
  4643. vk_instance_initialized = true;
  4644. if (debug_utils_ext) {
  4645. vk_instance.debug_utils_support = true;
  4646. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4647. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4648. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4649. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4650. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4651. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4652. }
  4653. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4654. vk_perf_logger_concurrent = getenv("GGML_VK_PERF_LOGGER_CONCURRENT") != nullptr;
  4655. vk_enable_sync_logger = getenv("GGML_VK_SYNC_LOGGER") != nullptr;
  4656. const char* GGML_VK_PERF_LOGGER_FREQUENCY = getenv("GGML_VK_PERF_LOGGER_FREQUENCY");
  4657. if (GGML_VK_PERF_LOGGER_FREQUENCY != nullptr) {
  4658. vk_perf_logger_frequency = std::stoul(GGML_VK_PERF_LOGGER_FREQUENCY);
  4659. }
  4660. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4661. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4662. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4663. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4664. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4665. if (devices_env != nullptr) {
  4666. size_t num_available_devices = devices.size();
  4667. std::string devices(devices_env);
  4668. std::replace(devices.begin(), devices.end(), ',', ' ');
  4669. std::stringstream ss(devices);
  4670. size_t tmp;
  4671. while (ss >> tmp) {
  4672. if(tmp >= num_available_devices) {
  4673. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4674. throw std::runtime_error("Invalid Vulkan device index");
  4675. }
  4676. vk_instance.device_indices.push_back(tmp);
  4677. }
  4678. } else {
  4679. // If no vulkan devices are found, return early
  4680. if (devices.empty()) {
  4681. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4682. return;
  4683. }
  4684. // Default to using all dedicated GPUs
  4685. for (size_t i = 0; i < devices.size(); i++) {
  4686. vk::PhysicalDeviceProperties2 new_props;
  4687. vk::PhysicalDeviceDriverProperties new_driver;
  4688. vk::PhysicalDeviceIDProperties new_id;
  4689. new_props.pNext = &new_driver;
  4690. new_driver.pNext = &new_id;
  4691. devices[i].getProperties2(&new_props);
  4692. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4693. // Check if there are two physical devices corresponding to the same GPU
  4694. auto old_device = std::find_if(
  4695. vk_instance.device_indices.begin(),
  4696. vk_instance.device_indices.end(),
  4697. [&devices, &new_id](const size_t k){
  4698. vk::PhysicalDeviceProperties2 old_props;
  4699. vk::PhysicalDeviceIDProperties old_id;
  4700. old_props.pNext = &old_id;
  4701. devices[k].getProperties2(&old_props);
  4702. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4703. equals = equals || (
  4704. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4705. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4706. );
  4707. return equals;
  4708. }
  4709. );
  4710. if (old_device == vk_instance.device_indices.end()) {
  4711. vk_instance.device_indices.push_back(i);
  4712. } else {
  4713. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4714. // This can cause error when splitting layers aross the devices, need to keep only 1
  4715. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4716. vk::PhysicalDeviceProperties2 old_props;
  4717. vk::PhysicalDeviceDriverProperties old_driver;
  4718. old_props.pNext = &old_driver;
  4719. devices[*old_device].getProperties2(&old_props);
  4720. std::map<vk::DriverId, int> driver_priorities {};
  4721. int old_priority = std::numeric_limits<int>::max();
  4722. int new_priority = std::numeric_limits<int>::max();
  4723. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4724. // Smaller number -> higher priority
  4725. switch (old_props.properties.vendorID) {
  4726. case VK_VENDOR_ID_AMD:
  4727. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4728. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4729. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4730. break;
  4731. case VK_VENDOR_ID_INTEL:
  4732. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4733. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4734. break;
  4735. case VK_VENDOR_ID_NVIDIA:
  4736. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4737. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4738. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4739. #endif
  4740. break;
  4741. }
  4742. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4743. if (driver_priorities.count(old_driver.driverID)) {
  4744. old_priority = driver_priorities[old_driver.driverID];
  4745. }
  4746. if (driver_priorities.count(new_driver.driverID)) {
  4747. new_priority = driver_priorities[new_driver.driverID];
  4748. }
  4749. if (new_priority < old_priority) {
  4750. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4751. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4752. vk_instance.device_indices.push_back(i);
  4753. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4754. }
  4755. else {
  4756. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4757. }
  4758. }
  4759. }
  4760. }
  4761. // If no GPUs found, fall back to the first non-CPU device.
  4762. // If only CPU devices are available, return without devices.
  4763. if (vk_instance.device_indices.empty()) {
  4764. for (size_t i = 0; i < devices.size(); i++) {
  4765. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4766. vk_instance.device_indices.push_back(i);
  4767. break;
  4768. }
  4769. }
  4770. }
  4771. if (vk_instance.device_indices.empty()) {
  4772. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4773. return;
  4774. }
  4775. }
  4776. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4777. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4778. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4779. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4780. bool membudget_supported = false;
  4781. for (const auto & ext : extensionprops) {
  4782. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4783. membudget_supported = true;
  4784. break;
  4785. }
  4786. }
  4787. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4788. ggml_vk_print_gpu_info(i);
  4789. }
  4790. }
  4791. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4792. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4793. ggml_vk_instance_init();
  4794. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4795. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4796. ctx->device = ggml_vk_get_device(idx);
  4797. ctx->semaphore_idx = 0;
  4798. ctx->event_idx = 0;
  4799. ctx->prealloc_size_x = 0;
  4800. ctx->prealloc_size_y = 0;
  4801. ctx->prealloc_size_split_k = 0;
  4802. // Fixed size of 1KB, for deterministic behavior
  4803. ctx->prealloc_size_add_rms_partials = 1024;
  4804. ctx->fence = ctx->device->device.createFence({});
  4805. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4806. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4807. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4808. if (vk_perf_logger_enabled) {
  4809. ctx->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  4810. }
  4811. #ifdef GGML_VULKAN_CHECK_RESULTS
  4812. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4813. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4814. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4815. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4816. #endif
  4817. }
  4818. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4819. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4820. switch (type) {
  4821. case GGML_TYPE_F32:
  4822. case GGML_TYPE_Q4_0:
  4823. case GGML_TYPE_Q4_1:
  4824. case GGML_TYPE_Q5_0:
  4825. case GGML_TYPE_Q5_1:
  4826. case GGML_TYPE_Q8_0:
  4827. case GGML_TYPE_Q2_K:
  4828. case GGML_TYPE_Q3_K:
  4829. case GGML_TYPE_Q4_K:
  4830. case GGML_TYPE_Q5_K:
  4831. case GGML_TYPE_Q6_K:
  4832. case GGML_TYPE_IQ1_S:
  4833. case GGML_TYPE_IQ1_M:
  4834. case GGML_TYPE_IQ2_XXS:
  4835. case GGML_TYPE_IQ2_XS:
  4836. case GGML_TYPE_IQ2_S:
  4837. case GGML_TYPE_IQ3_XXS:
  4838. case GGML_TYPE_IQ3_S:
  4839. case GGML_TYPE_IQ4_XS:
  4840. case GGML_TYPE_IQ4_NL:
  4841. case GGML_TYPE_MXFP4:
  4842. break;
  4843. default:
  4844. return nullptr;
  4845. }
  4846. return ctx->device->pipeline_dequant[type];
  4847. }
  4848. 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) {
  4849. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4850. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4851. return ctx->device->pipeline_matmul_f32;
  4852. }
  4853. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4854. return ctx->device->pipeline_matmul_f32_f16;
  4855. }
  4856. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4857. return ctx->device->pipeline_matmul_bf16;
  4858. }
  4859. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4860. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4861. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4862. }
  4863. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4864. return ctx->device->pipeline_matmul_f16.f16acc;
  4865. }
  4866. } else {
  4867. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4868. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4869. }
  4870. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4871. return ctx->device->pipeline_matmul_f16.f32acc;
  4872. }
  4873. }
  4874. // MMQ
  4875. if (src1_type == GGML_TYPE_Q8_1) {
  4876. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4877. if (pipelines->is_empty()) {
  4878. return nullptr;
  4879. }
  4880. return pipelines;
  4881. }
  4882. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4883. return nullptr;
  4884. }
  4885. switch (src0_type) {
  4886. case GGML_TYPE_Q4_0:
  4887. case GGML_TYPE_Q4_1:
  4888. case GGML_TYPE_Q5_0:
  4889. case GGML_TYPE_Q5_1:
  4890. case GGML_TYPE_Q8_0:
  4891. case GGML_TYPE_Q2_K:
  4892. case GGML_TYPE_Q3_K:
  4893. case GGML_TYPE_Q4_K:
  4894. case GGML_TYPE_Q5_K:
  4895. case GGML_TYPE_Q6_K:
  4896. case GGML_TYPE_IQ1_S:
  4897. case GGML_TYPE_IQ1_M:
  4898. case GGML_TYPE_IQ2_XXS:
  4899. case GGML_TYPE_IQ2_XS:
  4900. case GGML_TYPE_IQ2_S:
  4901. case GGML_TYPE_IQ3_XXS:
  4902. case GGML_TYPE_IQ3_S:
  4903. case GGML_TYPE_IQ4_XS:
  4904. case GGML_TYPE_IQ4_NL:
  4905. case GGML_TYPE_MXFP4:
  4906. break;
  4907. default:
  4908. return nullptr;
  4909. }
  4910. if (ctx->device->coopmat2) {
  4911. assert(src1_type == GGML_TYPE_F16);
  4912. return prec == GGML_PREC_DEFAULT ? ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f32acc;
  4913. }
  4914. if (ctx->device->coopmat_support) {
  4915. return (ctx->device->fp16 && ctx->device->coopmat_acc_f16_support && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  4916. }
  4917. return (ctx->device->fp16 && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  4918. }
  4919. 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, uint32_t m, uint32_t k) {
  4920. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4921. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4922. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4923. if (b_type == GGML_TYPE_Q8_1) {
  4924. switch (a_type) {
  4925. case GGML_TYPE_Q4_0:
  4926. case GGML_TYPE_Q4_1:
  4927. case GGML_TYPE_Q5_0:
  4928. case GGML_TYPE_Q5_1:
  4929. case GGML_TYPE_Q8_0:
  4930. case GGML_TYPE_MXFP4:
  4931. case GGML_TYPE_Q2_K:
  4932. case GGML_TYPE_Q3_K:
  4933. case GGML_TYPE_Q4_K:
  4934. case GGML_TYPE_Q5_K:
  4935. case GGML_TYPE_Q6_K:
  4936. case GGML_TYPE_IQ1_S:
  4937. case GGML_TYPE_IQ1_M:
  4938. break;
  4939. default:
  4940. return nullptr;
  4941. }
  4942. }
  4943. switch (a_type) {
  4944. case GGML_TYPE_F32:
  4945. case GGML_TYPE_F16:
  4946. case GGML_TYPE_BF16:
  4947. case GGML_TYPE_Q4_0:
  4948. case GGML_TYPE_Q4_1:
  4949. case GGML_TYPE_Q5_0:
  4950. case GGML_TYPE_Q5_1:
  4951. case GGML_TYPE_Q8_0:
  4952. case GGML_TYPE_Q2_K:
  4953. case GGML_TYPE_Q3_K:
  4954. case GGML_TYPE_Q4_K:
  4955. case GGML_TYPE_Q5_K:
  4956. case GGML_TYPE_Q6_K:
  4957. case GGML_TYPE_IQ1_S:
  4958. case GGML_TYPE_IQ1_M:
  4959. case GGML_TYPE_IQ2_XXS:
  4960. case GGML_TYPE_IQ2_XS:
  4961. case GGML_TYPE_IQ2_S:
  4962. case GGML_TYPE_IQ3_XXS:
  4963. case GGML_TYPE_IQ3_S:
  4964. case GGML_TYPE_IQ4_XS:
  4965. case GGML_TYPE_IQ4_NL:
  4966. case GGML_TYPE_MXFP4:
  4967. break;
  4968. default:
  4969. return nullptr;
  4970. }
  4971. // heuristic to choose workgroup size
  4972. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4973. if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4974. // Prefer larger workgroups when M is small, to spread the work out more
  4975. // and keep more SMs busy.
  4976. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4977. if (a_type == GGML_TYPE_Q6_K) {
  4978. if (m < 4096 && k >= 1024) {
  4979. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4980. }
  4981. } else {
  4982. if (m <= 8192 && k >= 1024) {
  4983. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4984. }
  4985. }
  4986. }
  4987. if (b_type == GGML_TYPE_Q8_1) {
  4988. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4989. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4990. }
  4991. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4992. }
  4993. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[dmmv_wg][a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[dmmv_wg][a_type][num_cols-1];
  4994. }
  4995. 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) {
  4996. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4997. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4998. return ctx->device->pipeline_matmul_id_f32;
  4999. }
  5000. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  5001. return ctx->device->pipeline_matmul_id_bf16;
  5002. }
  5003. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  5004. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  5005. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  5006. }
  5007. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  5008. return ctx->device->pipeline_matmul_id_f16.f16acc;
  5009. }
  5010. } else {
  5011. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  5012. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  5013. }
  5014. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  5015. return ctx->device->pipeline_matmul_id_f16.f32acc;
  5016. }
  5017. }
  5018. // MMQ
  5019. if (src1_type == GGML_TYPE_Q8_1) {
  5020. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  5021. if (pipelines->is_empty()) {
  5022. return nullptr;
  5023. }
  5024. return pipelines;
  5025. }
  5026. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  5027. switch (src0_type) {
  5028. case GGML_TYPE_Q4_0:
  5029. case GGML_TYPE_Q4_1:
  5030. case GGML_TYPE_Q5_0:
  5031. case GGML_TYPE_Q5_1:
  5032. case GGML_TYPE_Q8_0:
  5033. case GGML_TYPE_Q2_K:
  5034. case GGML_TYPE_Q3_K:
  5035. case GGML_TYPE_Q4_K:
  5036. case GGML_TYPE_Q5_K:
  5037. case GGML_TYPE_Q6_K:
  5038. case GGML_TYPE_IQ1_S:
  5039. case GGML_TYPE_IQ1_M:
  5040. case GGML_TYPE_IQ2_XXS:
  5041. case GGML_TYPE_IQ2_XS:
  5042. case GGML_TYPE_IQ2_S:
  5043. case GGML_TYPE_IQ3_XXS:
  5044. case GGML_TYPE_IQ3_S:
  5045. case GGML_TYPE_IQ4_XS:
  5046. case GGML_TYPE_IQ4_NL:
  5047. case GGML_TYPE_MXFP4:
  5048. break;
  5049. default:
  5050. return nullptr;
  5051. }
  5052. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  5053. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  5054. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  5055. bool support_fp16acc = !mmp.f16acc->is_empty();
  5056. bool support_fp32acc = !mmp.f32acc->is_empty();
  5057. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  5058. return mmp.f16acc;
  5059. } else {
  5060. GGML_ASSERT(support_fp32acc);
  5061. return mmp.f32acc;
  5062. }
  5063. }
  5064. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t m, uint32_t k) {
  5065. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  5066. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_Q8_1);
  5067. if (b_type == GGML_TYPE_Q8_1) {
  5068. switch (a_type) {
  5069. case GGML_TYPE_Q4_0:
  5070. case GGML_TYPE_Q4_1:
  5071. case GGML_TYPE_Q5_0:
  5072. case GGML_TYPE_Q5_1:
  5073. case GGML_TYPE_Q8_0:
  5074. case GGML_TYPE_MXFP4:
  5075. case GGML_TYPE_Q2_K:
  5076. case GGML_TYPE_Q3_K:
  5077. case GGML_TYPE_Q4_K:
  5078. case GGML_TYPE_Q5_K:
  5079. case GGML_TYPE_Q6_K:
  5080. case GGML_TYPE_IQ1_S:
  5081. case GGML_TYPE_IQ1_M:
  5082. break;
  5083. default:
  5084. return nullptr;
  5085. }
  5086. }
  5087. switch (a_type) {
  5088. case GGML_TYPE_F32:
  5089. case GGML_TYPE_F16:
  5090. case GGML_TYPE_BF16:
  5091. case GGML_TYPE_Q4_0:
  5092. case GGML_TYPE_Q4_1:
  5093. case GGML_TYPE_Q5_0:
  5094. case GGML_TYPE_Q5_1:
  5095. case GGML_TYPE_Q8_0:
  5096. case GGML_TYPE_Q2_K:
  5097. case GGML_TYPE_Q3_K:
  5098. case GGML_TYPE_Q4_K:
  5099. case GGML_TYPE_Q5_K:
  5100. case GGML_TYPE_Q6_K:
  5101. case GGML_TYPE_IQ1_S:
  5102. case GGML_TYPE_IQ1_M:
  5103. case GGML_TYPE_IQ2_XXS:
  5104. case GGML_TYPE_IQ2_XS:
  5105. case GGML_TYPE_IQ2_S:
  5106. case GGML_TYPE_IQ3_XXS:
  5107. case GGML_TYPE_IQ3_S:
  5108. case GGML_TYPE_IQ4_XS:
  5109. case GGML_TYPE_IQ4_NL:
  5110. case GGML_TYPE_MXFP4:
  5111. break;
  5112. default:
  5113. return nullptr;
  5114. }
  5115. // heuristic to choose workgroup size
  5116. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  5117. if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  5118. // Prefer larger workgroups when M is small, to spread the work out more
  5119. // and keep more SMs busy.
  5120. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  5121. if (a_type == GGML_TYPE_Q6_K) {
  5122. if (m < 4096 && k >= 1024) {
  5123. dmmv_wg = DMMV_WG_SIZE_LARGE;
  5124. }
  5125. } else {
  5126. if (m <= 8192 && k >= 1024) {
  5127. dmmv_wg = DMMV_WG_SIZE_LARGE;
  5128. }
  5129. }
  5130. }
  5131. if (b_type == GGML_TYPE_Q8_1) {
  5132. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  5133. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  5134. }
  5135. return ctx->device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[dmmv_wg][a_type];
  5136. }
  5137. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[dmmv_wg][a_type];
  5138. }
  5139. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  5140. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  5141. vk_buffer buf = ggml_vk_create_buffer(device, size,
  5142. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5143. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  5144. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  5145. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  5146. size/1024.0/1024.0);
  5147. device->device.freeMemory(buf->device_memory);
  5148. device->device.destroyBuffer(buf->buffer);
  5149. return nullptr;
  5150. }
  5151. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5152. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  5153. return buf->ptr;
  5154. }
  5155. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  5156. if (ptr == nullptr) {
  5157. return;
  5158. }
  5159. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  5160. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5161. vk_buffer buf;
  5162. size_t index;
  5163. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  5164. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  5165. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  5166. if (ptr >= addr && ptr < endr) {
  5167. buf = std::get<2>(device->pinned_memory[i]);
  5168. index = i;
  5169. break;
  5170. }
  5171. }
  5172. if (buf == nullptr) {
  5173. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  5174. return;
  5175. }
  5176. ggml_vk_destroy_buffer(buf);
  5177. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  5178. }
  5179. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  5180. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5181. buf = nullptr;
  5182. buf_offset = 0;
  5183. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  5184. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  5185. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  5186. if (ptr >= addr && ptr < endr) {
  5187. buf = std::get<2>(device->pinned_memory[i]);
  5188. buf_offset = ((const uint8_t *)ptr) - addr;
  5189. break;
  5190. }
  5191. }
  5192. }
  5193. static vk_subbuffer ggml_vk_tensor_subbuffer(
  5194. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  5195. vk_buffer buffer = nullptr;
  5196. size_t offset = 0;
  5197. if (ctx->device->uma) {
  5198. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  5199. }
  5200. if (!buffer) {
  5201. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  5202. buffer = buf_ctx->dev_buffer;
  5203. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  5204. }
  5205. GGML_ASSERT(buffer != nullptr);
  5206. size_t size = ggml_nbytes(tensor);
  5207. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  5208. // The shader must support misaligned offsets when indexing into the buffer
  5209. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  5210. offset &= ~misalign_bytes;
  5211. size += misalign_bytes;
  5212. return vk_subbuffer{buffer, offset, size};
  5213. }
  5214. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  5215. vk_submission s;
  5216. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  5217. if (one_time) {
  5218. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  5219. } else {
  5220. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  5221. }
  5222. return s;
  5223. }
  5224. template <typename T> size_t push_constant_size(const T &t) {
  5225. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5226. GGML_UNUSED(t);
  5227. return sizeof(T);
  5228. }
  5229. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  5230. GGML_UNUSED(t);
  5231. return sizeof(T) * t.size();
  5232. }
  5233. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  5234. GGML_UNUSED(t);
  5235. return sizeof(T) * N;
  5236. }
  5237. template <typename T> const T *push_constant_data(const T &t) {
  5238. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5239. return &t;
  5240. }
  5241. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  5242. return t.data();
  5243. }
  5244. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  5245. return t.data();
  5246. }
  5247. template <typename T>
  5248. 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, const T &push_constants, std::array<uint32_t, 3> elements) {
  5249. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  5250. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  5251. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  5252. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  5253. for (auto& buffer : descriptor_buffer_infos) {
  5254. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  5255. }
  5256. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  5257. GGML_ASSERT(wg0 <= ctx->device->properties.limits.maxComputeWorkGroupCount[0] &&
  5258. wg1 <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] &&
  5259. wg2 <= ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  5260. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  5261. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  5262. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  5263. GGML_ASSERT(pipeline->push_constant_size == push_constant_size(push_constants));
  5264. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  5265. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  5266. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  5267. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  5268. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  5269. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  5270. pipeline->layout,
  5271. 0,
  5272. { descriptor_set },
  5273. {});
  5274. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  5275. }
  5276. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  5277. s.buffer.end();
  5278. s.wait_semaphores = std::move(wait_semaphores);
  5279. s.signal_semaphores = std::move(signal_semaphores);
  5280. }
  5281. static void ggml_vk_ctx_end(vk_context& ctx) {
  5282. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  5283. if (ctx->s == nullptr) {
  5284. return;
  5285. }
  5286. ctx->s->buffer.end();
  5287. ctx->s = nullptr;
  5288. }
  5289. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  5290. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  5291. if (subctx->s != nullptr) {
  5292. ggml_vk_ctx_end(subctx);
  5293. }
  5294. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  5295. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  5296. }
  5297. static size_t ggml_vk_align_size(size_t width, size_t align) {
  5298. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  5299. return CEIL_DIV(width, align) * align;
  5300. }
  5301. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  5302. if (memcpys == nullptr) {
  5303. memcpy(dst, src, size);
  5304. } else {
  5305. memcpys->emplace_back(dst, src, size);
  5306. }
  5307. }
  5308. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  5309. if (memsets == nullptr) {
  5310. memset(dst, val, size);
  5311. } else {
  5312. memsets->emplace_back(dst, val, size);
  5313. }
  5314. }
  5315. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  5316. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  5317. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5318. ggml_vk_destroy_buffer(device->sync_staging);
  5319. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  5320. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5321. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5322. }
  5323. }
  5324. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  5325. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  5326. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5327. ggml_vk_destroy_buffer(ctx->sync_staging);
  5328. ctx->sync_staging = ggml_vk_create_buffer_check(ctx->device, size,
  5329. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5330. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5331. }
  5332. }
  5333. 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) {
  5334. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  5335. GGML_ASSERT(!ggml_is_contiguous(tensor));
  5336. // Buffer is already mapped
  5337. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5338. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5339. GGML_ABORT("fatal error");
  5340. }
  5341. // Check if src is pinned memory
  5342. vk_buffer buf = nullptr;
  5343. size_t buf_offset = 0;
  5344. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  5345. const uint64_t ne0 = tensor->ne[0];
  5346. const uint64_t ne1 = tensor->ne[1];
  5347. const uint64_t ne2 = tensor->ne[2];
  5348. const uint64_t ne3 = tensor->ne[3];
  5349. const uint64_t nb0 = tensor->nb[0];
  5350. const uint64_t nb1 = tensor->nb[1];
  5351. const uint64_t nb2 = tensor->nb[2];
  5352. const uint64_t nb3 = tensor->nb[3];
  5353. const ggml_type type = tensor->type;
  5354. const uint64_t ts = ggml_type_size(type);
  5355. const uint64_t bs = ggml_blck_size(type);
  5356. const uint64_t dstnb0 = ts;
  5357. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  5358. const uint64_t dstnb2 = dstnb1*ne1;
  5359. const uint64_t dstnb3 = dstnb2*ne2;
  5360. const uint64_t ne = ggml_nelements(tensor);
  5361. if (buf != nullptr) {
  5362. // Memory is pinned, use as staging buffer
  5363. std::vector<vk::BufferCopy> slices;
  5364. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5365. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5366. // Find longest contiguous slice
  5367. if (ne1*nb1 == dstnb2) {
  5368. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  5369. } else {
  5370. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5371. if (ne0*nb0/bs == dstnb1) {
  5372. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  5373. } else {
  5374. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5375. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5376. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5377. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  5378. }
  5379. }
  5380. }
  5381. }
  5382. }
  5383. }
  5384. ggml_vk_sync_buffers(ctx, subctx);
  5385. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5386. return;
  5387. }
  5388. if (!sync_staging) {
  5389. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5390. }
  5391. // Staging buffer required
  5392. vk_buffer& staging = ctx->device->sync_staging;
  5393. const uint64_t copy_size = ts*ne/bs;
  5394. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  5395. VkBufferCopy buf_copy{ 0, offset, copy_size };
  5396. ggml_vk_sync_buffers(ctx, subctx);
  5397. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5398. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5399. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5400. // Find longest contiguous slice
  5401. if (ne1*nb1 == dstnb2) {
  5402. 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);
  5403. } else {
  5404. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5405. if (ne0*nb0/bs == dstnb1) {
  5406. 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);
  5407. } else {
  5408. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5409. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5410. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5411. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  5412. }
  5413. }
  5414. }
  5415. }
  5416. }
  5417. }
  5418. }
  5419. static bool 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) {
  5420. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  5421. // Check if src is pinned memory
  5422. vk_buffer buf = nullptr;
  5423. size_t buf_offset = 0;
  5424. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  5425. if (buf != nullptr) {
  5426. // Memory is pinned, use as staging buffer
  5427. std::vector<vk::BufferCopy> slices(1);
  5428. if (width == spitch) {
  5429. // Only do single write if stride is equal
  5430. slices[0].srcOffset = buf_offset;
  5431. slices[0].dstOffset = offset;
  5432. slices[0].size = width * height;
  5433. } else {
  5434. slices.resize(height);
  5435. for (size_t i = 0; i < height; i++) {
  5436. slices[i].srcOffset = buf_offset + i * spitch;
  5437. slices[i].dstOffset = offset + i * width;
  5438. slices[i].size = width;
  5439. }
  5440. }
  5441. ggml_vk_sync_buffers(nullptr, subctx);
  5442. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5443. return true;
  5444. }
  5445. VK_LOG_DEBUG("STAGING");
  5446. if (!sync_staging) {
  5447. // copy was not handled caller needs to fall back
  5448. return false;
  5449. }
  5450. // Staging buffer required
  5451. const size_t copy_size = width*height;
  5452. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  5453. vk_buffer& staging_buffer = dst->device->sync_staging;
  5454. VkBufferCopy buf_copy = {
  5455. 0,
  5456. offset,
  5457. copy_size};
  5458. ggml_vk_sync_buffers(nullptr, subctx);
  5459. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5460. if (width == spitch) {
  5461. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  5462. } else {
  5463. for (size_t i = 0; i < height; i++) {
  5464. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  5465. }
  5466. }
  5467. return true;
  5468. }
  5469. static bool ggml_vk_buffer_write_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  5470. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  5471. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  5472. }
  5473. 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) {
  5474. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  5475. // Buffer is already mapped
  5476. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5477. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5478. for (size_t i = 0; i < height; i++) {
  5479. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  5480. }
  5481. } else {
  5482. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5483. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5484. ggml_vk_ctx_begin(dst->device, subctx);
  5485. bool ret = ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  5486. GGML_ASSERT(ret);
  5487. ggml_vk_ctx_end(subctx);
  5488. for (auto& cpy : subctx->in_memcpys) {
  5489. memcpy(cpy.dst, cpy.src, cpy.n);
  5490. }
  5491. for (auto& mset : subctx->memsets) {
  5492. memset(mset.dst, mset.val, mset.n);
  5493. }
  5494. ggml_vk_submit(subctx, dst->device->fence);
  5495. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  5496. dst->device->device.resetFences({ dst->device->fence });
  5497. ggml_vk_queue_command_pools_cleanup(dst->device);
  5498. }
  5499. }
  5500. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  5501. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  5502. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  5503. }
  5504. static bool 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) {
  5505. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  5506. GGML_ASSERT(width > 0);
  5507. GGML_ASSERT(height > 0);
  5508. GGML_ASSERT(src != nullptr);
  5509. // TODO: staging_offset is not used
  5510. // Check if dst is pinned memory
  5511. vk_buffer buf = nullptr;
  5512. size_t buf_offset = 0;
  5513. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  5514. std::vector<vk::BufferCopy> slices(1);
  5515. if (width == spitch && width == dpitch) {
  5516. // Only do single write if stride is equal
  5517. slices[0].srcOffset = offset;
  5518. slices[0].dstOffset = buf_offset;
  5519. slices[0].size = width * height;
  5520. } else {
  5521. slices.resize(height);
  5522. for (size_t i = 0; i < height; i++) {
  5523. slices[i].srcOffset = offset + i * spitch;
  5524. slices[i].dstOffset = buf_offset + i * dpitch;
  5525. slices[i].size = width;
  5526. }
  5527. }
  5528. if (buf != nullptr) {
  5529. // Memory is pinned, use as staging buffer
  5530. ggml_vk_sync_buffers(nullptr, subctx);
  5531. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5532. return true;
  5533. }
  5534. VK_LOG_DEBUG("STAGING");
  5535. if (!sync_staging) {
  5536. // copy was not handled caller needs to fall back
  5537. return false;
  5538. }
  5539. // Fall back to staging buffer
  5540. const size_t copy_size = dpitch * height;
  5541. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5542. vk_buffer& staging_buffer = src->device->sync_staging;
  5543. ggml_vk_sync_buffers(nullptr, subctx);
  5544. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5545. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5546. return true;
  5547. }
  5548. static bool ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  5549. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5550. }
  5551. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5552. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5553. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5554. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5555. // the HW device to host copy path.
  5556. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5557. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5558. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5559. } else {
  5560. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5561. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5562. ggml_vk_ctx_begin(src->device, subctx);
  5563. bool ret = ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5564. GGML_ASSERT(ret);
  5565. ggml_vk_ctx_end(subctx);
  5566. ggml_vk_submit(subctx, src->device->fence);
  5567. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5568. src->device->device.resetFences({ src->device->fence });
  5569. ggml_vk_queue_command_pools_cleanup(src->device);
  5570. for (auto& cpy : subctx->out_memcpys) {
  5571. memcpy(cpy.dst, cpy.src, cpy.n);
  5572. }
  5573. }
  5574. }
  5575. 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) {
  5576. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5577. // Make sure both buffers are on same device
  5578. GGML_ASSERT(src->device == dst->device);
  5579. VkBufferCopy bc{ src_offset, dst_offset, size };
  5580. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5581. }
  5582. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5583. if (src->device == dst->device) {
  5584. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5585. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5586. // Copy within the device
  5587. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5588. ggml_vk_ctx_begin(src->device, subctx);
  5589. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5590. ggml_vk_ctx_end(subctx);
  5591. ggml_vk_submit(subctx, src->device->fence);
  5592. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5593. src->device->device.resetFences({ src->device->fence });
  5594. ggml_vk_queue_command_pools_cleanup(src->device);
  5595. } else {
  5596. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5597. // Copy device to device
  5598. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5599. // Copy to src staging buffer
  5600. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5601. // Copy to dst buffer
  5602. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5603. }
  5604. }
  5605. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5606. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5607. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5608. dst->device->uma) {
  5609. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5610. return;
  5611. }
  5612. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5613. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5614. }
  5615. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5616. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5617. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5618. dst->device->uma) {
  5619. memset((uint8_t*)dst->ptr + offset, c, size);
  5620. return;
  5621. }
  5622. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5623. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5624. ggml_vk_ctx_begin(dst->device, subctx);
  5625. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5626. ggml_vk_ctx_end(subctx);
  5627. ggml_vk_submit(subctx, dst->device->fence);
  5628. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5629. dst->device->device.resetFences({ dst->device->fence });
  5630. ggml_vk_queue_command_pools_cleanup(dst->device);
  5631. }
  5632. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, bool disable_split_k, const vk_pipeline& pipeline) {
  5633. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5634. if (disable_split_k) {
  5635. return 1;
  5636. }
  5637. uint32_t split_k = 1;
  5638. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5639. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5640. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5641. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5642. if (k >= 2048) {
  5643. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5644. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5645. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5646. split_k = 3;
  5647. }
  5648. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5649. split_k = std::min(split_k, 8u);
  5650. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5651. // If this rounded up size would cause the last split to be empty,
  5652. // then reduce the split count.
  5653. while (true) {
  5654. if (split_k == 1) {
  5655. break;
  5656. }
  5657. uint32_t k_split = CEIL_DIV(k, split_k);
  5658. k_split = ROUNDUP_POW2(k_split, 256);
  5659. if (k_split * (split_k - 1) < k) {
  5660. break;
  5661. }
  5662. split_k--;
  5663. }
  5664. }
  5665. }
  5666. return split_k;
  5667. }
  5668. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, uint32_t m, uint32_t n, bool aligned, ggml_type src0_type, ggml_type src1_type) {
  5669. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5670. if (ctx->device->coopmat2) {
  5671. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5672. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5673. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5674. // Use large shader when the N dimension is greater than the medium shader's tile size
  5675. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5676. // Prefer large over medium if either:
  5677. // - medium or large tiles would overfill the GPU
  5678. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5679. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5680. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5681. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5682. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5683. if ((ctx->device->mul_mat_l[src0_type] && (n > crossover_large && prefer_large)) || (!ctx->device->mul_mat_m[src0_type] && !ctx->device->mul_mat_s[src0_type])) {
  5684. return aligned ? mmp->a_l : mmp->l;
  5685. }
  5686. // Use medium shader when the N dimension is greater than the small shader's tile size
  5687. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5688. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5689. return aligned ? mmp->a_m : mmp->m;
  5690. }
  5691. return aligned ? mmp->a_s : mmp->s;
  5692. }
  5693. if ((ctx->device->mul_mat_s[src0_type] && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_m[src0_type] && !ctx->device->mul_mat_l[src0_type])) {
  5694. return aligned ? mmp->a_s : mmp->s;
  5695. }
  5696. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5697. return aligned ? mmp->a_m : mmp->m;
  5698. }
  5699. return aligned ? mmp->a_l : mmp->l;
  5700. GGML_UNUSED(src1_type);
  5701. }
  5702. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type src0_type, ggml_type src1_type) {
  5703. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5704. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5705. }
  5706. static void ggml_vk_matmul(
  5707. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5708. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5709. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5710. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5711. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5712. uint32_t padded_n) {
  5713. 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 << ", padded_n: " << padded_n << ")");
  5714. if (split_k == 1) {
  5715. 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, padded_n };
  5716. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5717. return;
  5718. }
  5719. if (ctx->prealloc_split_k_need_sync) {
  5720. ggml_vk_sync_buffers(ctx, subctx);
  5721. }
  5722. GGML_ASSERT(batch_stride_d == m * n);
  5723. // Round the split size up to a multiple of 256 (k-quant alignment)
  5724. uint32_t k_split = CEIL_DIV(k, split_k);
  5725. k_split = ROUNDUP_POW2(k_split, 256);
  5726. 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, k_split, ne02, ne12, broadcast2, broadcast3, padded_n };
  5727. // Make sure enough workgroups get assigned for split k to work
  5728. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  5729. ggml_vk_sync_buffers(ctx, subctx);
  5730. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5731. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5732. ctx->prealloc_split_k_need_sync = true;
  5733. }
  5734. static vk_pipeline ggml_vk_guess_matmul_id_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, uint32_t m, uint32_t n, bool aligned, ggml_type src0_type) {
  5735. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5736. if (ctx->device->coopmat2) {
  5737. // Use large shader when the N dimension is greater than the medium shader's tile size
  5738. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5739. if ((ctx->device->mul_mat_id_l[src0_type] && (n > crossover_large)) || (!ctx->device->mul_mat_id_m[src0_type] && !ctx->device->mul_mat_id_s[src0_type])) {
  5740. return aligned ? mmp->a_l : mmp->l;
  5741. }
  5742. // Use medium shader when the N dimension is greater than the small shader's tile size
  5743. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5744. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5745. return aligned ? mmp->a_m : mmp->m;
  5746. }
  5747. return aligned ? mmp->a_s : mmp->s;
  5748. }
  5749. if ((ctx->device->mul_mat_id_s[src0_type] && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_id_m[src0_type] && !ctx->device->mul_mat_id_l[src0_type])) {
  5750. return aligned ? mmp->a_s : mmp->s;
  5751. }
  5752. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5753. return aligned ? mmp->a_m : mmp->m;
  5754. }
  5755. return aligned ? mmp->a_l : mmp->l;
  5756. }
  5757. static uint32_t ggml_vk_guess_matmul_id_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type src0_type) {
  5758. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5759. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5760. }
  5761. static void ggml_vk_matmul_id(
  5762. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5763. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids, const vk_subbuffer & expert_count_buf,
  5764. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5765. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5766. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5767. uint32_t padded_n) {
  5768. 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 << "), expert_count: (" << expert_count_buf.buffer->buffer << ", " << expert_count_buf.offset << ", " << expert_count_buf.size << "), " <<
  5769. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5770. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5771. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5772. 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,
  5773. nei0, nei1, nbi1, ne11, padded_n };
  5774. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids, expert_count_buf }, pc, { m, nei1, n_as });
  5775. }
  5776. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5777. return
  5778. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5779. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5780. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5781. }
  5782. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5783. // Choose "contiguous copy" shader if src/dst are contiguous
  5784. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5785. // Use optimized "transpose" shader if src dim1 is the innermost dimension.
  5786. bool transpose = dst && src->nb[1] == ggml_type_size(to) && ggml_are_same_shape(dst, src);
  5787. if (transpose && src->type == to) {
  5788. if (ggml_type_size(to) == 4) {
  5789. return ctx->device->pipeline_cpy_transpose_32;
  5790. } else if (ggml_type_size(to) == 2) {
  5791. return ctx->device->pipeline_cpy_transpose_16;
  5792. }
  5793. }
  5794. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5795. if (contig) {
  5796. return ctx->device->pipeline_contig_cpy_f32_f32;
  5797. } else {
  5798. return ctx->device->pipeline_cpy_f32_f32;
  5799. }
  5800. }
  5801. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5802. if (contig) {
  5803. return ctx->device->pipeline_contig_cpy_f32_f16;
  5804. } else {
  5805. return ctx->device->pipeline_cpy_f32_f16;
  5806. }
  5807. }
  5808. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5809. if (contig) {
  5810. return ctx->device->pipeline_contig_cpy_f16_f16;
  5811. } else {
  5812. return ctx->device->pipeline_cpy_f16_f16;
  5813. }
  5814. }
  5815. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5816. if (contig) {
  5817. return ctx->device->pipeline_contig_cpy_f16_f32;
  5818. } else {
  5819. return ctx->device->pipeline_cpy_f16_f32;
  5820. }
  5821. }
  5822. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5823. if (contig) {
  5824. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5825. } else {
  5826. return ctx->device->pipeline_cpy_f32_bf16;
  5827. }
  5828. }
  5829. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5830. if (contig) {
  5831. return ctx->device->pipeline_contig_cpy_f32_i32;
  5832. } else {
  5833. return ctx->device->pipeline_cpy_f32_i32;
  5834. }
  5835. }
  5836. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5837. if (contig) {
  5838. return ctx->device->pipeline_contig_cpy_i32_f32;
  5839. } else {
  5840. return ctx->device->pipeline_cpy_i32_f32;
  5841. }
  5842. }
  5843. if (src->type == GGML_TYPE_F32) {
  5844. switch (to) {
  5845. case GGML_TYPE_Q4_0:
  5846. case GGML_TYPE_Q4_1:
  5847. case GGML_TYPE_Q5_0:
  5848. case GGML_TYPE_Q5_1:
  5849. case GGML_TYPE_Q8_0:
  5850. case GGML_TYPE_IQ4_NL:
  5851. return ctx->device->pipeline_cpy_f32_quant[to];
  5852. default:
  5853. break;
  5854. }
  5855. }
  5856. if (to == GGML_TYPE_F32) {
  5857. switch (src->type) {
  5858. case GGML_TYPE_Q4_0:
  5859. case GGML_TYPE_Q4_1:
  5860. case GGML_TYPE_Q5_0:
  5861. case GGML_TYPE_Q5_1:
  5862. case GGML_TYPE_Q8_0:
  5863. case GGML_TYPE_IQ4_NL:
  5864. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5865. default:
  5866. break;
  5867. }
  5868. }
  5869. if (src->type == to) {
  5870. // Copy two or four bytes at a time, depending on block size.
  5871. // For quantized types, we scale by block size/type size. But
  5872. // this path is also used for bf16->bf16 for example, where the
  5873. // type size must be exactly 2 or 4.
  5874. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5875. if ((ggml_type_size(src->type) % 4) == 0) {
  5876. if (contig) {
  5877. return ctx->device->pipeline_contig_cpy_f32_f32;
  5878. } else {
  5879. return ctx->device->pipeline_cpy_f32_f32;
  5880. }
  5881. } else {
  5882. if (contig) {
  5883. return ctx->device->pipeline_contig_cpy_f16_f16;
  5884. } else {
  5885. return ctx->device->pipeline_cpy_f16_f16;
  5886. }
  5887. }
  5888. }
  5889. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5890. GGML_ABORT("fatal error");
  5891. }
  5892. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, const vk_subbuffer & in, const vk_subbuffer & out) {
  5893. 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] << "), ";
  5894. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5895. const int tensor_type_size = ggml_type_size(tensor->type);
  5896. const uint32_t ne = ggml_nelements(tensor);
  5897. std::array<uint32_t, 3> elements;
  5898. if (ne > 262144) {
  5899. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5900. } else if (ne > 512) {
  5901. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5902. } else {
  5903. elements = { ne, 1, 1 };
  5904. }
  5905. vk_op_unary_push_constants pc = {
  5906. (uint32_t)ne,
  5907. (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,
  5908. (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]),
  5909. 0,
  5910. 0.0f, 0.0f,
  5911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5912. };
  5913. init_pushconst_fastdiv(pc);
  5914. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5915. ggml_vk_sync_buffers(ctx, subctx);
  5916. }
  5917. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5918. switch(type) {
  5919. case GGML_TYPE_Q8_1:
  5920. return ctx->device->pipeline_quantize_q8_1_x4;
  5921. default:
  5922. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5923. GGML_ABORT("fatal error");
  5924. }
  5925. }
  5926. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer & in, const vk_subbuffer & out, uint32_t ne) {
  5927. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5928. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5929. const uint32_t num_blocks = CEIL_DIV(ne, pipeline->wg_denoms[0]);
  5930. // clamp the number of elements to the max workgroup count. The shader will iterate over the total number of blocks.
  5931. const uint64_t max_elements = std::min<uint64_t>(uint64_t{ctx->device->properties.limits.maxComputeWorkGroupCount[0]} * pipeline->wg_denoms[0], std::numeric_limits<uint32_t>::max());
  5932. const uint32_t elements = std::min(ne, static_cast<uint32_t>(max_elements));
  5933. const vk_quantize_q8_1_push_constants pc = {
  5934. ne,
  5935. num_blocks,
  5936. };
  5937. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, { elements, 1, 1 });
  5938. ggml_vk_sync_buffers(ctx, subctx);
  5939. }
  5940. 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 disable_split_k) {
  5941. VK_LOG_DEBUG("ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << ggml_type_name(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];
  5942. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << ggml_type_name(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];
  5943. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << ggml_type_name(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];
  5944. std::cerr << "))");
  5945. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5946. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5947. const uint64_t ne00 = src0->ne[0];
  5948. const uint64_t ne01 = src0->ne[1];
  5949. const uint64_t ne02 = src0->ne[2];
  5950. const uint64_t ne03 = src0->ne[3];
  5951. const uint64_t ne10 = src1->ne[0];
  5952. const uint64_t ne11 = src1->ne[1];
  5953. const uint64_t ne12 = src1->ne[2];
  5954. const uint64_t ne13 = src1->ne[3];
  5955. const uint64_t ne21 = dst->ne[1];
  5956. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5957. const uint32_t stride_batch_d = stride_d*ne21;
  5958. const uint64_t r2 = ne12 / ne02;
  5959. const uint64_t r3 = ne13 / ne03;
  5960. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5961. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5962. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5963. vk_buffer d_Qx = nullptr;
  5964. size_t qx_buf_offset = 0;
  5965. vk_buffer d_Qy = nullptr;
  5966. size_t qy_buf_offset = 0;
  5967. bool src0_uma = false;
  5968. bool src1_uma = false;
  5969. if (ctx->device->uma) {
  5970. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5971. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5972. src0_uma = d_Qx != nullptr;
  5973. src1_uma = d_Qy != nullptr;
  5974. }
  5975. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5976. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5977. !ggml_vk_dim01_contiguous(src0);
  5978. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5979. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5980. !ggml_vk_dim01_contiguous(src1);
  5981. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5982. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5983. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5984. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  5985. // Check for mmq first
  5986. vk_matmul_pipeline mmp = quantize_y ? ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, GGML_TYPE_Q8_1, (ggml_prec)dst->op_params[0]) : nullptr;
  5987. if (mmp == nullptr) {
  5988. // Fall back to f16 dequant mul mat
  5989. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5990. quantize_y = false;
  5991. }
  5992. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5993. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5994. if (qx_needs_dequant) {
  5995. // Fall back to dequant + f16 mulmat
  5996. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, f16_type, y_f32_kernel ? GGML_TYPE_F32 : f16_type, (ggml_prec)dst->op_params[0]);
  5997. }
  5998. // Not implemented
  5999. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6000. const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11, qx_needs_dequant ? f16_type : src0->type, quantize_y ? GGML_TYPE_Q8_1 : (y_f32_kernel ? GGML_TYPE_F32 : src1->type)));
  6001. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  6002. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned, qx_needs_dequant ? f16_type : src0->type, quantize_y ? GGML_TYPE_Q8_1 : (y_f32_kernel ? GGML_TYPE_F32 : src1->type));
  6003. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6004. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  6005. const uint64_t x_ne = ggml_nelements(src0);
  6006. // 128 elements per Q8_1 x4 block
  6007. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6008. const uint64_t d_ne = ggml_nelements(dst);
  6009. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  6010. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6011. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6012. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6013. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6014. const uint64_t d_sz = sizeof(float) * d_ne;
  6015. vk_pipeline to_fp16_vk_0 = nullptr;
  6016. vk_pipeline to_fp16_vk_1 = nullptr;
  6017. vk_pipeline to_q8_1 = nullptr;
  6018. if (x_non_contig) {
  6019. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6020. } else {
  6021. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6022. }
  6023. if (y_non_contig) {
  6024. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6025. } else {
  6026. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6027. }
  6028. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6029. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6030. if (quantize_y) {
  6031. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6032. }
  6033. {
  6034. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  6035. if (
  6036. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6037. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6038. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  6039. GGML_ABORT("Requested preallocation size is too large");
  6040. }
  6041. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6042. ctx->prealloc_size_x = x_sz;
  6043. ggml_vk_preallocate_buffers(ctx, subctx);
  6044. }
  6045. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6046. ctx->prealloc_size_y = y_sz;
  6047. ggml_vk_preallocate_buffers(ctx, subctx);
  6048. }
  6049. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  6050. ctx->prealloc_size_split_k = split_k_size;
  6051. ggml_vk_preallocate_buffers(ctx, subctx);
  6052. }
  6053. // Request descriptor sets
  6054. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6055. if (qx_needs_dequant) {
  6056. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6057. }
  6058. if (qy_needs_dequant) {
  6059. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6060. }
  6061. if (quantize_y) {
  6062. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6063. }
  6064. if (split_k > 1) {
  6065. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  6066. }
  6067. }
  6068. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6069. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6070. GGML_ASSERT(d_D != nullptr);
  6071. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  6072. vk_buffer d_X;
  6073. uint64_t x_buf_offset = 0;
  6074. vk_buffer d_Y;
  6075. uint64_t y_buf_offset = 0;
  6076. if (!src0_uma) {
  6077. d_Qx = src0_buf_ctx->dev_buffer;
  6078. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6079. GGML_ASSERT(d_Qx != nullptr);
  6080. }
  6081. if (!src1_uma) {
  6082. d_Qy = src1_buf_ctx->dev_buffer;
  6083. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6084. GGML_ASSERT(d_Qy != nullptr);
  6085. }
  6086. if (qx_needs_dequant) {
  6087. d_X = ctx->prealloc_x;
  6088. GGML_ASSERT(d_X->size >= x_sz);
  6089. } else {
  6090. d_X = d_Qx;
  6091. x_buf_offset = qx_buf_offset;
  6092. GGML_ASSERT(qx_sz == x_sz);
  6093. }
  6094. if (qy_needs_dequant) {
  6095. d_Y = ctx->prealloc_y;
  6096. GGML_ASSERT(d_Y->size >= y_sz);
  6097. } else if (quantize_y) {
  6098. d_Y = ctx->prealloc_y;
  6099. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6100. } else {
  6101. d_Y = d_Qy;
  6102. y_buf_offset = qy_buf_offset;
  6103. GGML_ASSERT(qy_sz == y_sz);
  6104. }
  6105. if (x_non_contig || qx_needs_dequant) {
  6106. if (ctx->prealloc_x_need_sync) {
  6107. ggml_vk_sync_buffers(ctx, subctx);
  6108. }
  6109. }
  6110. if (x_non_contig) {
  6111. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  6112. } else if (qx_needs_dequant) {
  6113. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6114. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)(x_ne), 1, 1});
  6115. ggml_vk_sync_buffers(ctx, subctx);
  6116. }
  6117. if (y_non_contig) {
  6118. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6119. ctx->prealloc_y_last_tensor_used != src1) {
  6120. if (ctx->prealloc_y_need_sync) {
  6121. ggml_vk_sync_buffers(ctx, subctx);
  6122. }
  6123. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  6124. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6125. ctx->prealloc_y_last_tensor_used = src1;
  6126. }
  6127. }
  6128. if (quantize_y) {
  6129. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6130. ctx->prealloc_y_last_tensor_used != src1) {
  6131. if (ctx->prealloc_y_need_sync) {
  6132. ggml_vk_sync_buffers(ctx, subctx);
  6133. }
  6134. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne);
  6135. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6136. ctx->prealloc_y_last_tensor_used = src1;
  6137. }
  6138. }
  6139. uint32_t stride_batch_x = ne00*ne01;
  6140. uint32_t stride_batch_y = ne10*ne11;
  6141. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6142. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6143. }
  6144. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6145. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6146. }
  6147. // compute
  6148. ggml_vk_matmul(
  6149. ctx, subctx, pipeline,
  6150. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6151. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  6152. ne01, ne11, ne10,
  6153. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  6154. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  6155. ); // NOLINT
  6156. if (x_non_contig || qx_needs_dequant) {
  6157. ctx->prealloc_x_need_sync = true;
  6158. }
  6159. if (y_non_contig || quantize_y) {
  6160. ctx->prealloc_y_need_sync = true;
  6161. }
  6162. }
  6163. // Device tuning
  6164. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  6165. if (device->mmvq_mode == 1) {
  6166. return true;
  6167. } else if (device->mmvq_mode == -1) {
  6168. return false;
  6169. }
  6170. // General performance issue with q3_k and q6_k due to 2-byte alignment
  6171. if (src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_Q6_K) {
  6172. return false;
  6173. }
  6174. // MMVQ is generally good for batches
  6175. if (n > 1) {
  6176. return true;
  6177. }
  6178. // Quantization overhead is not worth it for small k
  6179. switch (device->vendor_id) {
  6180. case VK_VENDOR_ID_NVIDIA:
  6181. if (src0_type == GGML_TYPE_Q2_K || src0_type == GGML_TYPE_IQ1_S || src0_type == GGML_TYPE_IQ1_M) {
  6182. return true;
  6183. }
  6184. if (k <= 4096) {
  6185. return false;
  6186. }
  6187. switch (src0_type) {
  6188. case GGML_TYPE_MXFP4:
  6189. case GGML_TYPE_Q8_0:
  6190. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  6191. default:
  6192. return true;
  6193. }
  6194. case VK_VENDOR_ID_AMD:
  6195. if (k < 2048) {
  6196. return false;
  6197. }
  6198. switch (src0_type) {
  6199. case GGML_TYPE_Q8_0:
  6200. return device->architecture == vk_device_architecture::AMD_GCN;
  6201. default:
  6202. return true;
  6203. }
  6204. case VK_VENDOR_ID_INTEL:
  6205. if (k < 2048) {
  6206. return false;
  6207. }
  6208. switch (src0_type) {
  6209. // From tests on A770 Linux, may need more tuning
  6210. case GGML_TYPE_Q4_0:
  6211. case GGML_TYPE_Q5_1:
  6212. return false;
  6213. default:
  6214. return true;
  6215. }
  6216. default:
  6217. return true;
  6218. }
  6219. GGML_UNUSED(m);
  6220. }
  6221. static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6222. ggml_tensor * dst = cgraph->nodes[node_idx];
  6223. const ggml_tensor * src0 = dst->src[0];
  6224. const ggml_tensor * src1 = dst->src[1];
  6225. 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];
  6226. 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];
  6227. 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];
  6228. std::cerr << ")),)");
  6229. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6230. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6231. const uint64_t ne00 = src0->ne[0];
  6232. const uint64_t ne01 = src0->ne[1];
  6233. const uint64_t ne02 = src0->ne[2];
  6234. const uint64_t ne03 = src0->ne[3];
  6235. const uint64_t ne10 = src1->ne[0];
  6236. const uint64_t ne11 = src1->ne[1];
  6237. const uint64_t ne12 = src1->ne[2];
  6238. const uint64_t ne13 = src1->ne[3];
  6239. const uint64_t ne20 = dst->ne[0];
  6240. const uint64_t ne21 = dst->ne[1];
  6241. // const uint64_t ne22 = dst->ne[2];
  6242. // const uint64_t ne23 = dst->ne[3];
  6243. const uint64_t r2 = ne12 / ne02;
  6244. const uint64_t r3 = ne13 / ne03;
  6245. // batch_n indicates that we need to compute a few vector results, and this assumes
  6246. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  6247. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  6248. bool batch_n = ne11 > 1;
  6249. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6250. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6251. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6252. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  6253. vk_pipeline to_fp16_vk_0 = nullptr;
  6254. vk_pipeline to_fp16_vk_1 = nullptr;
  6255. if (x_non_contig) {
  6256. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6257. }
  6258. if (y_non_contig) {
  6259. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6260. } else {
  6261. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6262. }
  6263. // Check for mmq first
  6264. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  6265. vk_pipeline to_q8_1 = nullptr;
  6266. if (dmmv == nullptr) {
  6267. // Fall back to f16 dequant mul mat
  6268. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  6269. quantize_y = false;
  6270. }
  6271. if (quantize_y) {
  6272. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6273. }
  6274. const bool qx_needs_dequant = x_non_contig;
  6275. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6276. // Not implemented
  6277. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6278. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6279. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6280. GGML_ASSERT(dmmv != nullptr);
  6281. const uint64_t x_ne = ggml_nelements(src0);
  6282. const uint64_t y_ne = ggml_nelements(src1);
  6283. 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);
  6284. 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;
  6285. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) :
  6286. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6287. {
  6288. if (
  6289. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6290. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6291. GGML_ABORT("Requested preallocation size is too large");
  6292. }
  6293. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6294. ctx->prealloc_size_x = x_sz;
  6295. ggml_vk_preallocate_buffers(ctx, subctx);
  6296. }
  6297. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6298. ctx->prealloc_size_y = y_sz;
  6299. ggml_vk_preallocate_buffers(ctx, subctx);
  6300. }
  6301. // Request descriptor sets
  6302. if (qx_needs_dequant) {
  6303. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6304. }
  6305. if (qy_needs_dequant) {
  6306. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6307. }
  6308. if (quantize_y) {
  6309. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6310. }
  6311. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6312. }
  6313. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6314. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6315. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6316. vk_subbuffer d_X, d_Y;
  6317. if (qx_needs_dequant) {
  6318. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6319. } else {
  6320. d_X = d_Qx;
  6321. GGML_ASSERT(qx_sz == x_sz);
  6322. }
  6323. if (qy_needs_dequant || quantize_y) {
  6324. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6325. } else {
  6326. d_Y = d_Qy;
  6327. }
  6328. if (x_non_contig) {
  6329. if (ctx->prealloc_x_need_sync) {
  6330. ggml_vk_sync_buffers(ctx, subctx);
  6331. }
  6332. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6333. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6334. }
  6335. if (y_non_contig) {
  6336. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6337. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6338. ctx->prealloc_y_last_tensor_used != src1) {
  6339. if (ctx->prealloc_y_need_sync) {
  6340. ggml_vk_sync_buffers(ctx, subctx);
  6341. }
  6342. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6343. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6344. ctx->prealloc_y_last_tensor_used = src1;
  6345. }
  6346. }
  6347. if (quantize_y) {
  6348. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6349. ctx->prealloc_y_last_tensor_used != src1) {
  6350. if (ctx->prealloc_y_need_sync) {
  6351. ggml_vk_sync_buffers(ctx, subctx);
  6352. }
  6353. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6354. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6355. ctx->prealloc_y_last_tensor_used = src1;
  6356. }
  6357. }
  6358. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  6359. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  6360. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  6361. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  6362. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6363. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6364. }
  6365. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6366. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6367. }
  6368. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6369. uint32_t groups_x = ne01;
  6370. uint32_t groups_z = 1;
  6371. if (ne01 > max_groups_x) {
  6372. groups_z = 64;
  6373. groups_x = CEIL_DIV(groups_x, groups_z);
  6374. }
  6375. uint32_t fusion_flags = 0;
  6376. vk_subbuffer d_F0 = d_D;
  6377. if (ctx->num_additional_fused_ops > 0) {
  6378. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6379. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6380. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6381. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6382. }
  6383. vk_subbuffer d_F1 = d_D;
  6384. if (ctx->num_additional_fused_ops == 2) {
  6385. const ggml_tensor * add = cgraph->nodes[node_idx + 2];
  6386. const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0];
  6387. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6388. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6389. }
  6390. // compute
  6391. const vk_mat_vec_push_constants pc = {
  6392. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6393. stride_batch_x, stride_batch_y, stride_batch_d,
  6394. fusion_flags,
  6395. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  6396. };
  6397. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6398. {
  6399. d_X,
  6400. d_Y,
  6401. d_D,
  6402. d_F0,
  6403. d_F1,
  6404. },
  6405. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  6406. if (x_non_contig) {
  6407. ctx->prealloc_x_need_sync = true;
  6408. }
  6409. if (y_non_contig || quantize_y) {
  6410. ctx->prealloc_y_need_sync = true;
  6411. }
  6412. }
  6413. static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6414. ggml_tensor * dst = cgraph->nodes[node_idx];
  6415. const ggml_tensor * src0 = dst->src[0];
  6416. const ggml_tensor * src1 = dst->src[1];
  6417. 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];
  6418. 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];
  6419. 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];
  6420. std::cerr << "))");
  6421. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  6422. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  6423. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  6424. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6425. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6426. const uint64_t ne00 = src0->ne[0];
  6427. const uint64_t ne01 = src0->ne[1];
  6428. const uint64_t ne02 = src0->ne[2];
  6429. // const uint64_t ne03 = src0->ne[3];
  6430. //const uint64_t ne10 = src1->ne[0];
  6431. const uint64_t ne11 = src1->ne[1];
  6432. const uint64_t ne12 = src1->ne[2];
  6433. // const uint64_t ne13 = src1->ne[3];
  6434. GGML_ASSERT(ne11 == 1);
  6435. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  6436. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  6437. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  6438. gqa_ratio = 1;
  6439. }
  6440. {
  6441. // Request descriptor sets
  6442. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  6443. }
  6444. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6445. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6446. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6447. vk_subbuffer d_F0 = d_D;
  6448. uint32_t fusion_flags = 0;
  6449. if (ctx->num_additional_fused_ops > 0) {
  6450. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6451. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6452. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6453. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6454. }
  6455. vk_subbuffer d_F1 = d_D;
  6456. if (ctx->num_additional_fused_ops > 1) {
  6457. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6458. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6459. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6460. }
  6461. // compute
  6462. vk_mat_vec_p021_push_constants pc = {
  6463. (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12,
  6464. 0, 0, fusion_flags
  6465. };
  6466. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6467. uint32_t workgroups_z = (uint32_t)ne12;
  6468. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  6469. if (gqa_ratio > 1) {
  6470. workgroups_z /= gqa_ratio;
  6471. }
  6472. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6473. {
  6474. d_Qx,
  6475. d_Qy,
  6476. d_D,
  6477. d_F0,
  6478. d_F1,
  6479. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6480. }
  6481. static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6482. ggml_tensor * dst = cgraph->nodes[node_idx];
  6483. const ggml_tensor * src0 = dst->src[0];
  6484. const ggml_tensor * src1 = dst->src[1];
  6485. 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];
  6486. 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];
  6487. 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];
  6488. std::cerr << "))");
  6489. GGML_ASSERT(!ggml_is_transposed(src0));
  6490. GGML_ASSERT(!ggml_is_transposed(src1));
  6491. GGML_ASSERT(!ggml_is_permuted(src0));
  6492. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6493. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6494. const uint64_t ne00 = src0->ne[0];
  6495. const uint64_t ne01 = src0->ne[1];
  6496. const uint64_t ne02 = src0->ne[2];
  6497. const uint64_t ne03 = src0->ne[3];
  6498. const uint64_t nb01 = src0->nb[1];
  6499. const uint64_t nb02 = src0->nb[2];
  6500. const uint64_t nb12 = src1->nb[2];
  6501. // const uint64_t ne10 = src1->ne[0];
  6502. const uint64_t ne11 = src1->ne[1];
  6503. const uint64_t ne12 = src1->ne[2];
  6504. // const uint64_t ne13 = src1->ne[3];
  6505. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6506. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6507. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6508. GGML_ASSERT(ne11 == 1);
  6509. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6510. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6511. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6512. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6513. {
  6514. // Request descriptor sets
  6515. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6516. }
  6517. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6518. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6519. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6520. vk_subbuffer d_F0 = d_D;
  6521. uint32_t fusion_flags = 0;
  6522. if (ctx->num_additional_fused_ops > 0) {
  6523. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6524. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6525. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6526. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6527. }
  6528. vk_subbuffer d_F1 = d_D;
  6529. if (ctx->num_additional_fused_ops > 1) {
  6530. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6531. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6532. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6533. }
  6534. // compute
  6535. vk_mat_vec_nc_push_constants pc = {
  6536. (uint32_t)ne00, (uint32_t)ne01,
  6537. row_stride_x, channel_stride_x, channel_stride_y,
  6538. (uint32_t)(ne12 / ne02), (uint32_t)ne12,
  6539. 0, 0,
  6540. nb03, nb13, nb23, fusion_flags
  6541. };
  6542. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6543. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6544. {
  6545. d_Qx,
  6546. d_Qy,
  6547. d_D,
  6548. d_F0,
  6549. d_F1,
  6550. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6551. }
  6552. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6553. ggml_tensor * dst = cgraph->nodes[node_idx];
  6554. ggml_tensor * src0 = dst->src[0];
  6555. ggml_tensor * src1 = dst->src[1];
  6556. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6557. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6558. // where the M dimension is very large.
  6559. // Split_k doesn't work with M splitting.
  6560. const size_t nbytes = ggml_nbytes(src0);
  6561. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6562. if (needs_split) {
  6563. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6564. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6565. uint32_t m_offset = 0;
  6566. while (m_offset < dst->ne[0]) {
  6567. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6568. ggml_tensor dst2 = *dst;
  6569. ggml_tensor src02 = *src0;
  6570. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6571. src02.view_src = src0->view_src ? src0->view_src : src0;
  6572. dst2.view_offs += m_offset * dst->nb[0];
  6573. src02.view_offs += m_offset * src0->nb[1];
  6574. dst2.ne[0] = cur_M_size;
  6575. src02.ne[1] = cur_M_size;
  6576. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6577. m_offset += cur_M_size;
  6578. }
  6579. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6580. // detect 0213 permutation, and batch size of 1
  6581. src0->nb[0] <= src0->nb[2] &&
  6582. src0->nb[2] <= src0->nb[1] &&
  6583. src0->nb[1] <= src0->nb[3] &&
  6584. src1->nb[0] <= src1->nb[2] &&
  6585. src1->nb[2] <= src1->nb[1] &&
  6586. src1->nb[1] <= src1->nb[3] &&
  6587. src0->ne[3] == 1 &&
  6588. src1->ne[3] == 1) {
  6589. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6590. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6591. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6592. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6593. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6594. // when ne12 and ne13 are one.
  6595. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6596. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6597. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6598. } else {
  6599. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6600. }
  6601. }
  6602. 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) {
  6603. 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];
  6604. 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];
  6605. 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];
  6606. 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] << "),)");
  6607. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6608. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6609. const uint64_t ne00 = src0->ne[0];
  6610. const uint64_t ne01 = src0->ne[1];
  6611. const uint64_t ne02 = src0->ne[2];
  6612. // const uint64_t ne03 = src0->ne[3];
  6613. const uint64_t ne10 = src1->ne[0];
  6614. const uint64_t ne11 = src1->ne[1];
  6615. const uint64_t ne12 = src1->ne[2];
  6616. const uint64_t ne13 = src1->ne[3];
  6617. const uint64_t nei0 = ids->ne[0];
  6618. const uint64_t nei1 = ids->ne[1];
  6619. const uint32_t nbi0 = ids->nb[0];
  6620. const uint32_t nbi1 = ids->nb[1];
  6621. const uint32_t nbi2 = ids->nb[2];
  6622. const uint64_t ne20 = dst->ne[0];
  6623. const uint64_t ne21 = dst->ne[1];
  6624. // const uint64_t ne22 = dst->ne[2];
  6625. // const uint64_t ne23 = dst->ne[3];
  6626. const uint64_t n_as = ne02;
  6627. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6628. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6629. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6630. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6631. vk_buffer d_Qx = nullptr;
  6632. size_t qx_buf_offset = 0;
  6633. vk_buffer d_Qy = nullptr;
  6634. size_t qy_buf_offset = 0;
  6635. vk_buffer d_ids = nullptr;
  6636. size_t ids_buf_offset = 0;
  6637. bool src0_uma = false;
  6638. bool src1_uma = false;
  6639. bool ids_uma = false;
  6640. if (ctx->device->uma) {
  6641. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6642. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6643. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6644. src0_uma = d_Qx != nullptr;
  6645. src1_uma = d_Qy != nullptr;
  6646. ids_uma = d_ids != nullptr;
  6647. }
  6648. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6649. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6650. !ggml_vk_dim01_contiguous(src0);
  6651. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6652. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6653. !ggml_vk_dim01_contiguous(src1);
  6654. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6655. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6656. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6657. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6658. // Check for mmq first
  6659. vk_matmul_pipeline mmp = quantize_y ? ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, GGML_TYPE_Q8_1, (ggml_prec)dst->op_params[0]) : nullptr;
  6660. if (mmp == nullptr) {
  6661. // Fall back to f16 dequant mul mat
  6662. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  6663. quantize_y = false;
  6664. }
  6665. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6666. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6667. if (qx_needs_dequant) {
  6668. // Fall back to dequant + f16 mulmat
  6669. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, f16_type, y_f32_kernel ? GGML_TYPE_F32 : f16_type, (ggml_prec)dst->op_params[0]);
  6670. }
  6671. // Not implemented
  6672. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6673. const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1, qx_needs_dequant ? f16_type : src0->type));
  6674. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6675. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6676. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6677. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6678. const uint64_t x_ne = ggml_nelements(src0);
  6679. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6680. const uint64_t d_ne = ggml_nelements(dst);
  6681. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6682. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6683. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6684. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6685. const uint64_t ids_sz = nbi2;
  6686. const uint64_t d_sz = sizeof(float) * d_ne;
  6687. vk_pipeline to_fp16_vk_0 = nullptr;
  6688. vk_pipeline to_fp16_vk_1 = nullptr;
  6689. vk_pipeline to_q8_1 = nullptr;
  6690. if (x_non_contig) {
  6691. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6692. } else {
  6693. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6694. }
  6695. if (y_non_contig) {
  6696. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6697. } else {
  6698. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6699. }
  6700. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6701. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6702. if (quantize_y) {
  6703. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6704. }
  6705. vk_pipeline count_experts = ctx->device->pipeline_count_experts;
  6706. uint32_t expert_count_size = sizeof(uint32_t) * n_as;
  6707. {
  6708. if (
  6709. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6710. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6711. GGML_ABORT("Requested preallocation size is too large");
  6712. }
  6713. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6714. ctx->prealloc_size_x = x_sz;
  6715. ggml_vk_preallocate_buffers(ctx, subctx);
  6716. }
  6717. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6718. ctx->prealloc_size_y = y_sz;
  6719. ggml_vk_preallocate_buffers(ctx, subctx);
  6720. }
  6721. if (ctx->prealloc_size_split_k < expert_count_size) {
  6722. ctx->prealloc_size_split_k = expert_count_size;
  6723. ggml_vk_preallocate_buffers(ctx, subctx);
  6724. }
  6725. // Request descriptor sets
  6726. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6727. if (qx_needs_dequant) {
  6728. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6729. }
  6730. if (qy_needs_dequant) {
  6731. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6732. }
  6733. if (quantize_y) {
  6734. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6735. }
  6736. ggml_pipeline_request_descriptor_sets(ctx, count_experts, 1);
  6737. }
  6738. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6739. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6740. GGML_ASSERT(d_D != nullptr);
  6741. vk_buffer d_X;
  6742. uint64_t x_buf_offset = 0;
  6743. vk_buffer d_Y;
  6744. uint64_t y_buf_offset = 0;
  6745. if (!src0_uma) {
  6746. d_Qx = src0_buf_ctx->dev_buffer;
  6747. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6748. GGML_ASSERT(d_Qx != nullptr);
  6749. }
  6750. if (!src1_uma) {
  6751. d_Qy = src1_buf_ctx->dev_buffer;
  6752. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6753. GGML_ASSERT(d_Qy != nullptr);
  6754. }
  6755. if (!ids_uma) {
  6756. d_ids = ids_buf_ctx->dev_buffer;
  6757. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6758. GGML_ASSERT(d_ids != nullptr);
  6759. }
  6760. if (qx_needs_dequant) {
  6761. d_X = ctx->prealloc_x;
  6762. GGML_ASSERT(d_X->size >= x_sz);
  6763. } else {
  6764. d_X = d_Qx;
  6765. x_buf_offset = qx_buf_offset;
  6766. GGML_ASSERT(qx_sz == x_sz);
  6767. }
  6768. if (qy_needs_dequant) {
  6769. d_Y = ctx->prealloc_y;
  6770. GGML_ASSERT(d_Y->size >= y_sz);
  6771. } else if (quantize_y) {
  6772. d_Y = ctx->prealloc_y;
  6773. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6774. } else {
  6775. d_Y = d_Qy;
  6776. y_buf_offset = qy_buf_offset;
  6777. GGML_ASSERT(qy_sz == y_sz);
  6778. }
  6779. if (x_non_contig || qx_needs_dequant) {
  6780. if (ctx->prealloc_x_need_sync) {
  6781. ggml_vk_sync_buffers(ctx, subctx);
  6782. }
  6783. }
  6784. // Count how many times each expert is used
  6785. vk_subbuffer expert_count_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  6786. if (ctx->prealloc_split_k_need_sync) {
  6787. ggml_vk_sync_buffers(ctx, subctx);
  6788. }
  6789. {
  6790. const std::vector<uint32_t> pc = { (uint32_t)nei0,
  6791. (uint32_t)nei1,
  6792. (uint32_t)(nbi0 / ggml_type_size(ids->type)),
  6793. (uint32_t)(nbi1 / ggml_type_size(ids->type)),
  6794. (uint32_t)(get_misalign_bytes(ctx, ids) / ggml_type_size(ids->type)) };
  6795. ggml_vk_dispatch_pipeline(ctx, subctx, count_experts,
  6796. { vk_subbuffer{ d_ids, ids_buf_offset, ids_sz }, expert_count_buf }, pc, { (uint32_t)n_as, 1, 1});
  6797. }
  6798. if (x_non_contig) {
  6799. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  6800. } else if (qx_needs_dequant) {
  6801. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6802. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6803. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6804. }
  6805. if (y_non_contig) {
  6806. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6807. ctx->prealloc_y_last_tensor_used != src1) {
  6808. if (ctx->prealloc_y_need_sync) {
  6809. ggml_vk_sync_buffers(ctx, subctx);
  6810. }
  6811. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  6812. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6813. ctx->prealloc_y_last_tensor_used = src1;
  6814. }
  6815. }
  6816. if (quantize_y) {
  6817. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6818. ctx->prealloc_y_last_tensor_used != src1) {
  6819. if (ctx->prealloc_y_need_sync) {
  6820. ggml_vk_sync_buffers(ctx, subctx);
  6821. }
  6822. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne);
  6823. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6824. ctx->prealloc_y_last_tensor_used = src1;
  6825. }
  6826. }
  6827. ggml_vk_sync_buffers(ctx, subctx);
  6828. uint32_t stride_batch_x = ne00*ne01;
  6829. uint32_t stride_batch_y = ne10*ne11;
  6830. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6831. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6832. }
  6833. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6834. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6835. }
  6836. // compute
  6837. ggml_vk_matmul_id(
  6838. ctx, subctx, pipeline,
  6839. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6840. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz }, expert_count_buf,
  6841. ne01, ne21, ne10, ne10, ne10, ne01,
  6842. stride_batch_x, stride_batch_y, ne20*ne21,
  6843. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6844. ); // NOLINT
  6845. if (x_non_contig || qx_needs_dequant) {
  6846. ctx->prealloc_x_need_sync = true;
  6847. }
  6848. if (y_non_contig || quantize_y) {
  6849. ctx->prealloc_y_need_sync = true;
  6850. }
  6851. ctx->prealloc_split_k_need_sync = true;
  6852. }
  6853. static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6854. ggml_tensor * dst = cgraph->nodes[node_idx];
  6855. ggml_tensor * src0 = dst->src[0];
  6856. ggml_tensor * src1 = dst->src[1];
  6857. ggml_tensor * ids = dst->src[2];
  6858. 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];
  6859. 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];
  6860. 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];
  6861. 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];
  6862. std::cerr << "))");
  6863. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6864. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6865. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6866. const uint64_t ne00 = src0->ne[0];
  6867. const uint64_t ne01 = src0->ne[1];
  6868. // const uint64_t ne02 = src0->ne[2];
  6869. // const uint64_t ne03 = src0->ne[3];
  6870. const uint64_t ne10 = src1->ne[0];
  6871. const uint64_t ne11 = src1->ne[1];
  6872. const uint64_t ne12 = src1->ne[2];
  6873. // const uint64_t ne13 = src1->ne[3];
  6874. const uint64_t nei0 = ids->ne[0];
  6875. const uint64_t nei1 = ids->ne[1];
  6876. GGML_ASSERT(nei1 == 1);
  6877. const uint64_t ne20 = dst->ne[0];
  6878. const uint64_t ne21 = dst->ne[1];
  6879. // const uint64_t ne22 = dst->ne[2];
  6880. // const uint64_t ne23 = dst->ne[3];
  6881. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6882. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6883. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6884. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne12, ne10, src0->type);
  6885. vk_pipeline to_fp16_vk_0 = nullptr;
  6886. vk_pipeline to_fp16_vk_1 = nullptr;
  6887. if (x_non_contig) {
  6888. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6889. }
  6890. if (y_non_contig) {
  6891. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6892. } else {
  6893. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6894. }
  6895. // Check for mmq first
  6896. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00) : nullptr;
  6897. vk_pipeline to_q8_1 = nullptr;
  6898. if (dmmv == nullptr) {
  6899. // Fall back to f16 dequant mul mat
  6900. dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00);
  6901. quantize_y = false;
  6902. }
  6903. if (quantize_y) {
  6904. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6905. }
  6906. const bool qx_needs_dequant = x_non_contig;
  6907. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6908. // Not implemented
  6909. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6910. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6911. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6912. GGML_ASSERT(dmmv != nullptr);
  6913. const uint64_t x_ne = ggml_nelements(src0);
  6914. const uint64_t y_ne = ggml_nelements(src1);
  6915. 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);
  6916. 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;
  6917. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) :
  6918. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6919. {
  6920. if (
  6921. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6922. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6923. GGML_ABORT("Requested preallocation size is too large");
  6924. }
  6925. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6926. ctx->prealloc_size_x = x_sz;
  6927. ggml_vk_preallocate_buffers(ctx, subctx);
  6928. }
  6929. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6930. ctx->prealloc_size_y = y_sz;
  6931. ggml_vk_preallocate_buffers(ctx, subctx);
  6932. }
  6933. // Request descriptor sets
  6934. if (qx_needs_dequant) {
  6935. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6936. }
  6937. if (qy_needs_dequant) {
  6938. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6939. }
  6940. if (quantize_y) {
  6941. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6942. }
  6943. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6944. }
  6945. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6946. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6947. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6948. vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids);
  6949. vk_subbuffer d_F0 = d_D;
  6950. vk_subbuffer d_X, d_Y;
  6951. if (qx_needs_dequant) {
  6952. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6953. } else {
  6954. d_X = d_Qx;
  6955. }
  6956. if (qy_needs_dequant || quantize_y) {
  6957. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6958. } else {
  6959. d_Y = d_Qy;
  6960. }
  6961. if (x_non_contig) {
  6962. if (ctx->prealloc_x_need_sync) {
  6963. ggml_vk_sync_buffers(ctx, subctx);
  6964. }
  6965. }
  6966. if (x_non_contig) {
  6967. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6968. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6969. }
  6970. if (y_non_contig) {
  6971. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6972. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6973. ctx->prealloc_y_last_tensor_used != src1) {
  6974. if (ctx->prealloc_y_need_sync) {
  6975. ggml_vk_sync_buffers(ctx, subctx);
  6976. }
  6977. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6978. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6979. ctx->prealloc_y_last_tensor_used = src1;
  6980. }
  6981. }
  6982. if (quantize_y) {
  6983. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6984. ctx->prealloc_y_last_tensor_used != src1) {
  6985. if (ctx->prealloc_y_need_sync) {
  6986. ggml_vk_sync_buffers(ctx, subctx);
  6987. }
  6988. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6989. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6990. ctx->prealloc_y_last_tensor_used = src1;
  6991. }
  6992. }
  6993. uint32_t stride_batch_y = ne10*ne11;
  6994. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6995. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6996. }
  6997. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6998. uint32_t groups_x = ne01;
  6999. uint32_t groups_z = 1;
  7000. if (ne01 > max_groups_x) {
  7001. groups_z = 64;
  7002. groups_x = CEIL_DIV(groups_x, groups_z);
  7003. }
  7004. uint32_t fusion_flags = 0;
  7005. if (ctx->num_additional_fused_ops > 0) {
  7006. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  7007. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  7008. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  7009. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0;
  7010. } else {
  7011. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  7012. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  7013. }
  7014. }
  7015. vk_subbuffer d_F1 = d_D;
  7016. if (ctx->num_additional_fused_ops > 1) {
  7017. const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1];
  7018. d_F1 = ggml_vk_tensor_subbuffer(ctx, scale);
  7019. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
  7020. }
  7021. // compute
  7022. const vk_mat_vec_id_push_constants pc = {
  7023. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  7024. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  7025. fusion_flags,
  7026. (uint32_t)nei0, (uint32_t)ne11,
  7027. };
  7028. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  7029. {
  7030. d_X,
  7031. d_Y,
  7032. d_D,
  7033. d_F0,
  7034. d_F1,
  7035. d_ids,
  7036. },
  7037. pc, { groups_x, (uint32_t)nei0, groups_z });
  7038. if (x_non_contig) {
  7039. ctx->prealloc_x_need_sync = true;
  7040. }
  7041. if (y_non_contig || quantize_y) {
  7042. ctx->prealloc_y_need_sync = true;
  7043. }
  7044. }
  7045. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  7046. ggml_tensor * dst = cgraph->nodes[node_idx];
  7047. ggml_tensor * src0 = dst->src[0];
  7048. ggml_tensor * src2 = dst->src[2];
  7049. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  7050. }
  7051. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  7052. ggml_tensor * dst = cgraph->nodes[node_idx];
  7053. ggml_tensor * src0 = dst->src[0];
  7054. ggml_tensor * src1 = dst->src[1];
  7055. ggml_tensor * src2 = dst->src[2];
  7056. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  7057. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  7058. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  7059. } else {
  7060. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  7061. }
  7062. }
  7063. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool small_cache) {
  7064. // Needs to be kept up to date on shader changes
  7065. GGML_UNUSED(hsv);
  7066. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  7067. const uint32_t Br = get_fa_scalar_num_large_rows(hsk, hsv, small_cache);
  7068. const uint32_t Bc = scalar_flash_attention_Bc;
  7069. const uint32_t tmpsh = wg_size * sizeof(float);
  7070. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  7071. const uint32_t masksh = Bc * Br * sizeof(float);
  7072. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  7073. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  7074. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  7075. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  7076. return supported;
  7077. }
  7078. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  7079. // Needs to be kept up to date on shader changes
  7080. GGML_UNUSED(hsv);
  7081. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  7082. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  7083. const uint32_t Bc = scalar_flash_attention_Bc;
  7084. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  7085. const uint32_t acctype = f32acc ? 4 : 2;
  7086. const uint32_t f16vec4 = 8;
  7087. const uint32_t tmpsh = wg_size * sizeof(float);
  7088. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  7089. const uint32_t qstride = hsk_pad / 4 + 2;
  7090. const uint32_t Qf = Br * qstride * f16vec4;
  7091. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  7092. const uint32_t sfsh = Bc * sfshstride * acctype;
  7093. const uint32_t kshstride = hsk_pad / 4 + 2;
  7094. const uint32_t ksh = Bc * kshstride * f16vec4;
  7095. const uint32_t slope = Br * sizeof(float);
  7096. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  7097. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  7098. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  7099. return supported;
  7100. }
  7101. 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, const ggml_tensor * sinks, ggml_tensor * dst) {
  7102. 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];
  7103. 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];
  7104. 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];
  7105. 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];
  7106. if (sinks) {
  7107. std::cerr << "), (" << sinks << ", name=" << sinks->name << ", type=" << sinks->type << ", ne0=" << sinks->ne[0] << ", ne1=" << sinks->ne[1] << ", ne2=" << sinks->ne[2] << ", ne3=" << sinks->ne[3] << ", nb0=" << sinks->nb[0] << ", nb1=" << sinks->nb[1] << ", nb2=" << sinks->nb[2] << ", nb3=" << sinks->nb[3];
  7108. }
  7109. std::cerr << "))");
  7110. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  7111. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  7112. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  7113. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  7114. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  7115. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  7116. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  7117. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  7118. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  7119. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  7120. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  7121. const uint32_t HSK = nek0;
  7122. const uint32_t HSV = nev0;
  7123. uint32_t N = neq1;
  7124. const uint32_t KV = nek1;
  7125. GGML_ASSERT(ne0 == HSV);
  7126. GGML_ASSERT(ne2 == N);
  7127. // input tensor rows must be contiguous
  7128. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  7129. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  7130. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  7131. GGML_ASSERT(neq0 == HSK);
  7132. GGML_ASSERT(neq1 == N);
  7133. GGML_ASSERT(nev1 == nek1);
  7134. // dst cannot be transposed or permuted
  7135. GGML_ASSERT(nb0 == sizeof(float));
  7136. GGML_ASSERT(nb0 <= nb1);
  7137. GGML_ASSERT(nb1 <= nb2);
  7138. GGML_ASSERT(nb2 <= nb3);
  7139. assert(dst->type == GGML_TYPE_F32);
  7140. assert(q->type == GGML_TYPE_F32);
  7141. assert(k->type == v->type);
  7142. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  7143. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  7144. if (path == FA_COOPMAT1) {
  7145. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  7146. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  7147. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  7148. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  7149. path = FA_SCALAR;
  7150. }
  7151. }
  7152. uint32_t gqa_ratio = 1;
  7153. uint32_t qk_ratio = neq2 / nek2;
  7154. uint32_t workgroups_x = (uint32_t)neq1;
  7155. uint32_t workgroups_y = (uint32_t)neq2;
  7156. uint32_t workgroups_z = (uint32_t)neq3;
  7157. const bool small_cache = nek1 < 1024;
  7158. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  7159. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  7160. uint32_t max_gqa;
  7161. switch (path) {
  7162. case FA_SCALAR:
  7163. case FA_COOPMAT1:
  7164. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  7165. max_gqa = get_fa_scalar_num_large_rows(HSK, HSV, small_cache);
  7166. break;
  7167. case FA_COOPMAT2:
  7168. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  7169. break;
  7170. default:
  7171. GGML_ASSERT(0);
  7172. }
  7173. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  7174. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  7175. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  7176. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  7177. // and change addressing calculations to index Q's dimension 2.
  7178. gqa_ratio = qk_ratio;
  7179. N = gqa_ratio;
  7180. workgroups_y /= N;
  7181. }
  7182. bool small_rows = N <= get_fa_num_small_rows(path);
  7183. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  7184. // So use scalar instead.
  7185. if (small_rows && path == FA_COOPMAT1) {
  7186. path = FA_SCALAR;
  7187. }
  7188. // scalar is faster than coopmat2 when N==1
  7189. if (N == 1 && path == FA_COOPMAT2) {
  7190. path = FA_SCALAR;
  7191. }
  7192. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  7193. if (path == FA_SCALAR &&
  7194. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV, small_cache)) {
  7195. small_rows = true;
  7196. }
  7197. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  7198. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  7199. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  7200. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  7201. if (k->type == GGML_TYPE_F32) {
  7202. k_stride /= 4;
  7203. }
  7204. if (v->type == GGML_TYPE_F32) {
  7205. v_stride /= 4;
  7206. }
  7207. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows, small_cache);
  7208. bool aligned = (KV % alignment) == 0 &&
  7209. // the "aligned" shader variant will forcibly align strides, for performance
  7210. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  7211. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  7212. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  7213. aligned = false;
  7214. }
  7215. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  7216. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, small_cache, path, aligned, f32acc);
  7217. vk_pipeline pipeline = nullptr;
  7218. {
  7219. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7220. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  7221. auto it = pipelines.find(fa_pipeline_state);
  7222. if (it != pipelines.end()) {
  7223. pipeline = it->second;
  7224. } else {
  7225. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7226. }
  7227. }
  7228. assert(pipeline);
  7229. uint32_t split_kv = KV;
  7230. uint32_t split_k = 1;
  7231. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  7232. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  7233. // Try to use split_k when KV is large enough to be worth the overhead
  7234. if (workgroups_x == 1 && shader_core_count > 0) {
  7235. // Try to run two workgroups per SM.
  7236. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  7237. if (split_k > 1) {
  7238. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  7239. // of "align", so recompute split_k based on that.
  7240. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  7241. split_k = CEIL_DIV(KV, split_kv);
  7242. workgroups_x = split_k;
  7243. }
  7244. }
  7245. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  7246. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  7247. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  7248. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  7249. GGML_ABORT("Requested preallocation size is too large");
  7250. }
  7251. if (ctx->prealloc_size_split_k < split_k_size) {
  7252. ctx->prealloc_size_split_k = split_k_size;
  7253. ggml_vk_preallocate_buffers(ctx, subctx);
  7254. }
  7255. {
  7256. // Request descriptor sets
  7257. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7258. if (split_k > 1) {
  7259. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  7260. }
  7261. }
  7262. float scale = 1.0f;
  7263. float max_bias = 0.0f;
  7264. float logit_softcap = 0.0f;
  7265. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  7266. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  7267. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  7268. if (logit_softcap != 0) {
  7269. scale /= logit_softcap;
  7270. }
  7271. const uint32_t n_head_kv = neq2;
  7272. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  7273. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  7274. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  7275. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  7276. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  7277. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  7278. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  7279. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  7280. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  7281. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  7282. const vk_flash_attn_push_constants pc = { N, KV,
  7283. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  7284. (uint32_t)neq2, (uint32_t)neq3,
  7285. (uint32_t)nek2, (uint32_t)nek3,
  7286. (uint32_t)nev2, (uint32_t)nev3,
  7287. nem1, nem2, nem3,
  7288. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  7289. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  7290. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  7291. scale, max_bias, logit_softcap,
  7292. mask_n_head_log2, m0, m1,
  7293. gqa_ratio, split_kv, split_k };
  7294. if (split_k > 1) {
  7295. if (ctx->prealloc_split_k_need_sync) {
  7296. ggml_vk_sync_buffers(ctx, subctx);
  7297. }
  7298. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  7299. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7300. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  7301. // We only use split_k when group query attention is enabled, which means
  7302. // there's no more than one tile of rows (i.e. workgroups_x would have been
  7303. // one). We reuse workgroups_x to mean the number of splits, so we need to
  7304. // cancel out the divide by wg_denoms[0].
  7305. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  7306. ggml_vk_sync_buffers(ctx, subctx);
  7307. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  7308. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  7309. {split_k_buf, sinks_buf, dst_buf},
  7310. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  7311. ctx->prealloc_split_k_need_sync = true;
  7312. } else {
  7313. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7314. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  7315. pc, { workgroups_x, workgroups_y, workgroups_z });
  7316. }
  7317. }
  7318. static vk_conv_shapes ggml_vk_conv_select_shape(ggml_backend_vk_context * ctx, uint32_t K, uint32_t NPQ) {
  7319. auto n_tiles = [&](vk_conv_shapes s) {
  7320. return CEIL_DIV(K, vk_conv_block_sizes[s].K)
  7321. * CEIL_DIV(NPQ, vk_conv_block_sizes[s].NPQ);
  7322. };
  7323. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7324. // so small convolutions will still choose a smaller tile.
  7325. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7326. if (K > 64 && n_tiles(CONV_SHAPE_128x128) >= shader_core_count * 2) {
  7327. return CONV_SHAPE_128x128;
  7328. } else if (K <= 32 && n_tiles(CONV_SHAPE_32x256) >= shader_core_count * 2) {
  7329. return CONV_SHAPE_32x256;
  7330. } else {
  7331. return CONV_SHAPE_64x32;
  7332. }
  7333. }
  7334. 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, const ggml_tensor * dst, ggml_op op) {
  7335. switch (op) {
  7336. case GGML_OP_GET_ROWS:
  7337. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  7338. if (src0->type == GGML_TYPE_I32) {
  7339. // i32 src only supports i32 result
  7340. GGML_ASSERT(dst->type == GGML_TYPE_I32);
  7341. return ctx->device->pipeline_get_rows[src0->type];
  7342. }
  7343. if (dst->type == GGML_TYPE_F16) {
  7344. return ctx->device->pipeline_get_rows[src0->type];
  7345. }
  7346. if (dst->type == GGML_TYPE_F32) {
  7347. return ctx->device->pipeline_get_rows_f32[src0->type];
  7348. }
  7349. return nullptr;
  7350. case GGML_OP_ACC:
  7351. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7352. return ctx->device->pipeline_acc_f32;
  7353. }
  7354. return nullptr;
  7355. case GGML_OP_ADD:
  7356. case GGML_OP_SUB:
  7357. case GGML_OP_MUL:
  7358. case GGML_OP_DIV:
  7359. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7360. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  7361. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  7362. return nullptr;
  7363. }
  7364. switch (op) {
  7365. case GGML_OP_ADD:
  7366. {
  7367. if (ctx->num_additional_fused_ops > 0) {
  7368. if (ctx->do_add_rms_partials) {
  7369. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  7370. } else {
  7371. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  7372. }
  7373. }
  7374. if (ctx->do_add_rms_partials) {
  7375. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  7376. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7377. } else {
  7378. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  7379. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7380. }
  7381. }
  7382. case GGML_OP_SUB:
  7383. {
  7384. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  7385. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7386. }
  7387. case GGML_OP_MUL:
  7388. {
  7389. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  7390. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7391. }
  7392. case GGML_OP_DIV:
  7393. {
  7394. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  7395. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7396. }
  7397. default:
  7398. break;
  7399. }
  7400. return nullptr;
  7401. case GGML_OP_ADD_ID:
  7402. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7403. return ctx->device->pipeline_add_id_f32;
  7404. }
  7405. return nullptr;
  7406. case GGML_OP_CONCAT:
  7407. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7408. return ctx->device->pipeline_concat_f32;
  7409. }
  7410. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7411. return ctx->device->pipeline_concat_f16;
  7412. }
  7413. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7414. return ctx->device->pipeline_concat_i32;
  7415. }
  7416. return nullptr;
  7417. case GGML_OP_UPSCALE:
  7418. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7419. uint32_t mode = (ggml_get_op_params_i32(dst, 0) & (0xFF | GGML_SCALE_FLAG_ANTIALIAS));
  7420. switch (mode) {
  7421. case GGML_SCALE_MODE_NEAREST:
  7422. return ctx->device->pipeline_upscale_nearest_f32;
  7423. case GGML_SCALE_MODE_BILINEAR:
  7424. return ctx->device->pipeline_upscale_bilinear_f32;
  7425. case GGML_SCALE_MODE_BICUBIC:
  7426. return ctx->device->pipeline_upscale_bicubic_f32;
  7427. case GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS:
  7428. return ctx->device->pipeline_upscale_bilinear_antialias_f32;
  7429. default:
  7430. return nullptr;
  7431. }
  7432. }
  7433. return nullptr;
  7434. case GGML_OP_SCALE:
  7435. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7436. return ctx->device->pipeline_scale_f32;
  7437. }
  7438. return nullptr;
  7439. case GGML_OP_SQR:
  7440. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7441. return ctx->device->pipeline_sqr_f32;
  7442. }
  7443. return nullptr;
  7444. case GGML_OP_SQRT:
  7445. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7446. return ctx->device->pipeline_sqrt_f32;
  7447. }
  7448. return nullptr;
  7449. case GGML_OP_SIN:
  7450. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7451. return ctx->device->pipeline_sin_f32;
  7452. }
  7453. return nullptr;
  7454. case GGML_OP_COS:
  7455. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7456. return ctx->device->pipeline_cos_f32;
  7457. }
  7458. return nullptr;
  7459. case GGML_OP_LOG:
  7460. if (src0->type == dst->type &&
  7461. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7462. return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16];
  7463. }
  7464. return nullptr;
  7465. case GGML_OP_TRI:
  7466. if (src0->type == dst->type &&
  7467. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7468. return ctx->device->pipeline_tri[dst->type == GGML_TYPE_F16];
  7469. }
  7470. return nullptr;
  7471. case GGML_OP_DIAG:
  7472. if (src0->type == dst->type &&
  7473. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7474. return ctx->device->pipeline_diag[dst->type == GGML_TYPE_F16];
  7475. }
  7476. return nullptr;
  7477. case GGML_OP_CLAMP:
  7478. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7479. return ctx->device->pipeline_clamp_f32;
  7480. }
  7481. return nullptr;
  7482. case GGML_OP_PAD:
  7483. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7484. return ctx->device->pipeline_pad_f32;
  7485. }
  7486. return nullptr;
  7487. case GGML_OP_ROLL:
  7488. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7489. return ctx->device->pipeline_roll_f32;
  7490. }
  7491. return nullptr;
  7492. case GGML_OP_REPEAT:
  7493. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7494. return ctx->device->pipeline_repeat_f32;
  7495. }
  7496. return nullptr;
  7497. case GGML_OP_REPEAT_BACK:
  7498. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7499. return ctx->device->pipeline_repeat_back_f32;
  7500. }
  7501. return nullptr;
  7502. case GGML_OP_CPY:
  7503. case GGML_OP_CONT:
  7504. case GGML_OP_DUP:
  7505. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7506. case GGML_OP_SET_ROWS:
  7507. if (src1->type == GGML_TYPE_I64) {
  7508. return ctx->device->pipeline_set_rows_i64[dst->type];
  7509. } else {
  7510. return ctx->device->pipeline_set_rows_i32[dst->type];
  7511. }
  7512. case GGML_OP_SILU_BACK:
  7513. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7514. return ctx->device->pipeline_silu_back_f32;
  7515. }
  7516. return nullptr;
  7517. case GGML_OP_NORM:
  7518. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7519. return ctx->device->pipeline_norm_f32;
  7520. }
  7521. return nullptr;
  7522. case GGML_OP_GROUP_NORM:
  7523. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7524. return ctx->device->pipeline_group_norm_f32;
  7525. }
  7526. return nullptr;
  7527. case GGML_OP_RMS_NORM:
  7528. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7529. if (ctx->do_add_rms_partials) {
  7530. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7531. } else {
  7532. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7533. }
  7534. }
  7535. return nullptr;
  7536. case GGML_OP_RMS_NORM_BACK:
  7537. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7538. return ctx->device->pipeline_rms_norm_back_f32;
  7539. }
  7540. return nullptr;
  7541. case GGML_OP_L2_NORM:
  7542. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7543. return ctx->device->pipeline_l2_norm_f32;
  7544. }
  7545. return nullptr;
  7546. case GGML_OP_UNARY:
  7547. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7548. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7549. (src0->type != dst->type)) {
  7550. return nullptr;
  7551. }
  7552. switch (ggml_get_unary_op(dst)) {
  7553. case GGML_UNARY_OP_EXP:
  7554. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7555. case GGML_UNARY_OP_SILU:
  7556. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7557. case GGML_UNARY_OP_GELU:
  7558. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7559. case GGML_UNARY_OP_GELU_ERF:
  7560. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7561. case GGML_UNARY_OP_GELU_QUICK:
  7562. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7563. case GGML_UNARY_OP_RELU:
  7564. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7565. case GGML_UNARY_OP_XIELU:
  7566. return ctx->device->pipeline_xielu[dst->type == GGML_TYPE_F16];
  7567. case GGML_UNARY_OP_NEG:
  7568. return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16];
  7569. case GGML_UNARY_OP_TANH:
  7570. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7571. case GGML_UNARY_OP_SIGMOID:
  7572. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7573. case GGML_UNARY_OP_HARDSIGMOID:
  7574. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7575. case GGML_UNARY_OP_HARDSWISH:
  7576. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7577. case GGML_UNARY_OP_ABS:
  7578. return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16];
  7579. case GGML_UNARY_OP_SOFTPLUS:
  7580. return ctx->device->pipeline_softplus[dst->type == GGML_TYPE_F16];
  7581. case GGML_UNARY_OP_STEP:
  7582. return ctx->device->pipeline_step[dst->type == GGML_TYPE_F16];
  7583. case GGML_UNARY_OP_ROUND:
  7584. return ctx->device->pipeline_round[dst->type == GGML_TYPE_F16];
  7585. case GGML_UNARY_OP_CEIL:
  7586. return ctx->device->pipeline_ceil[dst->type == GGML_TYPE_F16];
  7587. case GGML_UNARY_OP_FLOOR:
  7588. return ctx->device->pipeline_floor[dst->type == GGML_TYPE_F16];
  7589. case GGML_UNARY_OP_TRUNC:
  7590. return ctx->device->pipeline_trunc[dst->type == GGML_TYPE_F16];
  7591. default:
  7592. break;
  7593. }
  7594. return nullptr;
  7595. case GGML_OP_GLU:
  7596. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7597. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7598. (src0->type != dst->type)) {
  7599. return nullptr;
  7600. }
  7601. switch (ggml_get_glu_op(dst)) {
  7602. case GGML_GLU_OP_GEGLU:
  7603. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7604. case GGML_GLU_OP_REGLU:
  7605. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7606. case GGML_GLU_OP_SWIGLU:
  7607. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7608. case GGML_GLU_OP_SWIGLU_OAI:
  7609. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7610. case GGML_GLU_OP_GEGLU_ERF:
  7611. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7612. case GGML_GLU_OP_GEGLU_QUICK:
  7613. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7614. default:
  7615. break;
  7616. }
  7617. return nullptr;
  7618. case GGML_OP_DIAG_MASK_INF:
  7619. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7620. return ctx->device->pipeline_diag_mask_inf_f32;
  7621. }
  7622. return nullptr;
  7623. case GGML_OP_SOFT_MAX:
  7624. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7625. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7626. if (ctx->num_additional_fused_ops) {
  7627. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7628. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7629. // use n_experts from push constant if it's not equal to the power of two spec constant
  7630. bool use_push = dst->ne[0] != (1u << idx);
  7631. return ctx->device->pipeline_topk_moe[idx][use_push];
  7632. }
  7633. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7634. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7635. }
  7636. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7637. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7638. }
  7639. return nullptr;
  7640. case GGML_OP_SOFT_MAX_BACK:
  7641. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7642. return ctx->device->pipeline_soft_max_back_f32;
  7643. }
  7644. return nullptr;
  7645. case GGML_OP_ROPE:
  7646. case GGML_OP_ROPE_BACK:
  7647. {
  7648. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7649. const int mode = ((const int32_t *) rope->op_params)[2];
  7650. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7651. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7652. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7653. if (is_neox) {
  7654. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7655. return ctx->device->pipeline_rope_neox_f32;
  7656. }
  7657. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7658. return ctx->device->pipeline_rope_neox_f32_f16;
  7659. }
  7660. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7661. return ctx->device->pipeline_rope_neox_f16;
  7662. }
  7663. } else if (is_mrope && !is_vision) {
  7664. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7665. return ctx->device->pipeline_rope_multi_f32;
  7666. }
  7667. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7668. return ctx->device->pipeline_rope_multi_f32_f16;
  7669. }
  7670. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7671. return ctx->device->pipeline_rope_multi_f16;
  7672. }
  7673. } else if (is_vision) {
  7674. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7675. return ctx->device->pipeline_rope_vision_f32;
  7676. }
  7677. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7678. return ctx->device->pipeline_rope_vision_f16;
  7679. }
  7680. } else {
  7681. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7682. return ctx->device->pipeline_rope_norm_f32;
  7683. }
  7684. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7685. return ctx->device->pipeline_rope_norm_f32_f16;
  7686. }
  7687. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7688. return ctx->device->pipeline_rope_norm_f16;
  7689. }
  7690. }
  7691. return nullptr;
  7692. }
  7693. case GGML_OP_SUM:
  7694. case GGML_OP_SUM_ROWS:
  7695. case GGML_OP_MEAN:
  7696. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7697. return ctx->device->pipeline_sum_rows_f32;
  7698. }
  7699. return nullptr;
  7700. case GGML_OP_CUMSUM:
  7701. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7702. if (src0->ne[0] <= 512) {
  7703. return ctx->device->pipeline_cumsum_small_f32;
  7704. } else {
  7705. return ctx->device->pipeline_cumsum_f32;
  7706. }
  7707. }
  7708. return nullptr;
  7709. case GGML_OP_SOLVE_TRI:
  7710. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7711. vk_solve_tri_pipeline_state solve_tri_pipeline_state(src0->ne[0], src1->ne[0]);
  7712. vk_pipeline pipeline = nullptr;
  7713. {
  7714. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7715. auto it = ctx->device->pipeline_solve_tri_f32.find(solve_tri_pipeline_state);
  7716. if (it != ctx->device->pipeline_solve_tri_f32.end()) {
  7717. pipeline = it->second;
  7718. } else {
  7719. ctx->device->pipeline_solve_tri_f32[solve_tri_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7720. }
  7721. }
  7722. return pipeline;
  7723. }
  7724. return nullptr;
  7725. case GGML_OP_ARGMAX:
  7726. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7727. return ctx->device->pipeline_argmax_f32;
  7728. }
  7729. return nullptr;
  7730. case GGML_OP_COUNT_EQUAL:
  7731. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7732. return ctx->device->pipeline_count_equal_i32;
  7733. }
  7734. return nullptr;
  7735. case GGML_OP_IM2COL:
  7736. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7737. return ctx->device->pipeline_im2col_f32;
  7738. }
  7739. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7740. return ctx->device->pipeline_im2col_f32_f16;
  7741. }
  7742. return nullptr;
  7743. case GGML_OP_IM2COL_3D:
  7744. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7745. return ctx->device->pipeline_im2col_3d_f32;
  7746. }
  7747. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7748. return ctx->device->pipeline_im2col_3d_f32_f16;
  7749. }
  7750. return nullptr;
  7751. case GGML_OP_TIMESTEP_EMBEDDING:
  7752. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7753. return ctx->device->pipeline_timestep_embedding_f32;
  7754. }
  7755. return nullptr;
  7756. case GGML_OP_CONV_TRANSPOSE_1D:
  7757. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7758. return ctx->device->pipeline_conv_transpose_1d_f32;
  7759. }
  7760. return nullptr;
  7761. case GGML_OP_POOL_2D:
  7762. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7763. return ctx->device->pipeline_pool2d_f32;
  7764. }
  7765. return nullptr;
  7766. case GGML_OP_RWKV_WKV6:
  7767. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7768. return ctx->device->pipeline_rwkv_wkv6_f32;
  7769. }
  7770. return nullptr;
  7771. case GGML_OP_RWKV_WKV7:
  7772. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7773. return ctx->device->pipeline_rwkv_wkv7_f32;
  7774. }
  7775. return nullptr;
  7776. case GGML_OP_SSM_SCAN:
  7777. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7778. const uint32_t d_state = src0->ne[0];
  7779. if (d_state == 128) {
  7780. return ctx->device->pipeline_ssm_scan_f32_d128;
  7781. } else if (d_state == 256) {
  7782. return ctx->device->pipeline_ssm_scan_f32_d256;
  7783. }
  7784. }
  7785. return nullptr;
  7786. case GGML_OP_SSM_CONV:
  7787. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7788. return ctx->device->pipeline_ssm_conv_f32;
  7789. }
  7790. return nullptr;
  7791. case GGML_OP_OPT_STEP_ADAMW:
  7792. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7793. return ctx->device->pipeline_opt_step_adamw_f32;
  7794. }
  7795. return nullptr;
  7796. case GGML_OP_OPT_STEP_SGD:
  7797. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7798. return ctx->device->pipeline_opt_step_sgd_f32;
  7799. }
  7800. return nullptr;
  7801. case GGML_OP_LEAKY_RELU:
  7802. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7803. return ctx->device->pipeline_leaky_relu_f32;
  7804. }
  7805. return nullptr;
  7806. case GGML_OP_CONV_2D:
  7807. case GGML_OP_CONV_TRANSPOSE_2D:
  7808. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7809. uint32_t K = dst->ne[2]; // Cout
  7810. uint32_t NPQ = dst->ne[3] * dst->ne[1] * dst->ne[0]; // N * OH * OW
  7811. vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, K, NPQ);
  7812. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  7813. uint32_t KW = (uint32_t)src0->ne[0];
  7814. uint32_t KH = (uint32_t)src0->ne[1];
  7815. uint32_t s0 = (uint32_t)(ggml_get_op_params_i32(dst, 0));
  7816. uint32_t s1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 1) : s0;
  7817. uint32_t p0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0;
  7818. uint32_t p1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 3) : 0;
  7819. uint32_t d0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 4) : 1;
  7820. uint32_t d1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 5) : 1;
  7821. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7822. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7823. if (op == GGML_OP_CONV_2D) {
  7824. if (src0->type == GGML_TYPE_F32) {
  7825. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7826. } else if (src0->type == GGML_TYPE_F16) {
  7827. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7828. }
  7829. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7830. if (src0->type == GGML_TYPE_F32) {
  7831. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7832. } else if (src0->type == GGML_TYPE_F16) {
  7833. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7834. }
  7835. }
  7836. vk_pipeline pipeline = nullptr;
  7837. {
  7838. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7839. auto it = pipelines->find(conv2d_pipeline_state);
  7840. if (it != pipelines->end()) {
  7841. pipeline = it->second;
  7842. } else {
  7843. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7844. }
  7845. }
  7846. return pipeline;
  7847. }
  7848. return nullptr;
  7849. case GGML_OP_CONV_2D_DW:
  7850. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7851. if (ggml_is_contiguous(src1)) {
  7852. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7853. } else if (ggml_is_contiguous_channels(src1)) {
  7854. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7855. }
  7856. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7857. if (ggml_is_contiguous(src1)) {
  7858. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7859. } else if (ggml_is_contiguous_channels(src1)) {
  7860. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7861. }
  7862. }
  7863. return nullptr;
  7864. case GGML_OP_ADD1:
  7865. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7866. return ctx->device->pipeline_add1_f16_f16;
  7867. }
  7868. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7869. return ctx->device->pipeline_add1_f16_f32;
  7870. }
  7871. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7872. return ctx->device->pipeline_add1_f32_f32;
  7873. }
  7874. return nullptr;
  7875. case GGML_OP_ARANGE:
  7876. if (dst->type == GGML_TYPE_F32) {
  7877. return ctx->device->pipeline_arange_f32;
  7878. }
  7879. return nullptr;
  7880. case GGML_OP_FILL:
  7881. if (dst->type == GGML_TYPE_F32) {
  7882. return ctx->device->pipeline_fill_f32;
  7883. }
  7884. return nullptr;
  7885. default:
  7886. return nullptr;
  7887. }
  7888. GGML_UNUSED(src2);
  7889. }
  7890. 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, const ggml_tensor * src3, ggml_tensor * dst) {
  7891. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7892. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7893. p.misalign_offsets = (a_offset << 16) | d_offset;
  7894. GGML_UNUSED(src1);
  7895. GGML_UNUSED(src2);
  7896. GGML_UNUSED(src3);
  7897. }
  7898. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_sum_rows_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7899. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7900. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7901. p.misalign_offsets = (a_offset << 16) | d_offset;
  7902. GGML_UNUSED(src1);
  7903. GGML_UNUSED(src2);
  7904. GGML_UNUSED(src3);
  7905. }
  7906. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_pad_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7907. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7908. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7909. p.misalign_offsets = (a_offset << 16) | d_offset;
  7910. GGML_UNUSED(src1);
  7911. GGML_UNUSED(src2);
  7912. GGML_UNUSED(src3);
  7913. }
  7914. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_im2col_3d_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7915. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7916. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7917. p.misalign_offsets = (a_offset << 16) | d_offset;
  7918. GGML_UNUSED(src0);
  7919. GGML_UNUSED(src2);
  7920. GGML_UNUSED(src3);
  7921. }
  7922. 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, const ggml_tensor * src3, ggml_tensor * dst) {
  7923. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7924. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7925. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7926. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7927. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7928. GGML_UNUSED(src2);
  7929. GGML_UNUSED(src3);
  7930. }
  7931. 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, const ggml_tensor * src3, ggml_tensor * dst) {
  7932. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7933. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7934. p.a_offset = a_offset;
  7935. p.d_offset = d_offset;
  7936. GGML_UNUSED(src1);
  7937. GGML_UNUSED(src2);
  7938. GGML_UNUSED(src3);
  7939. }
  7940. template<typename PC>
  7941. 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, const ggml_tensor * src3, ggml_tensor * dst, ggml_op op, PC&& pc) {
  7942. 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];
  7943. if (src1 != nullptr) {
  7944. 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];
  7945. }
  7946. if (src2 != nullptr) {
  7947. 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];
  7948. }
  7949. if (src3 != nullptr) {
  7950. std::cerr << "), (" << src3 << ", name=" << src3->name << ", type=" << src3->type << ", ne0=" << src3->ne[0] << ", ne1=" << src3->ne[1] << ", ne2=" << src3->ne[2] << ", ne3=" << src3->ne[3] << ", nb0=" << src3->nb[0] << ", nb1=" << src3->nb[1] << ", nb2=" << src3->nb[2] << ", nb3=" << src3->nb[3];
  7951. }
  7952. 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];
  7953. std::cerr << "), " << ggml_op_name(op) << ")");
  7954. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7955. GGML_ASSERT(dst->buffer != nullptr);
  7956. const uint64_t ne00 = src0->ne[0];
  7957. const uint64_t ne01 = src0->ne[1];
  7958. const uint64_t ne02 = src0->ne[2];
  7959. const uint64_t ne03 = src0->ne[3];
  7960. const bool use_src1 = src1 != nullptr;
  7961. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7962. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7963. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7964. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7965. const bool use_src2 = src2 != nullptr;
  7966. const bool use_src3 = src3 != nullptr;
  7967. init_pushconst_fastdiv(pc);
  7968. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7969. if (pipeline == nullptr) {
  7970. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7971. if (src1 != nullptr) {
  7972. std::cerr << " and " << ggml_type_name(src1->type);
  7973. }
  7974. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7975. GGML_ABORT("fatal error");
  7976. }
  7977. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7978. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true);
  7979. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, true) : vk_subbuffer{};
  7980. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, true) : vk_subbuffer{};
  7981. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, true) : vk_subbuffer{};
  7982. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
  7983. // Compute misalignment offset for descriptors and store it in in push constants.
  7984. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7985. std::array<uint32_t, 3> elements;
  7986. switch (op) {
  7987. case GGML_OP_NORM:
  7988. case GGML_OP_RMS_NORM_BACK:
  7989. case GGML_OP_L2_NORM:
  7990. case GGML_OP_SOFT_MAX:
  7991. case GGML_OP_SOFT_MAX_BACK:
  7992. case GGML_OP_SUM_ROWS:
  7993. case GGML_OP_CUMSUM:
  7994. case GGML_OP_MEAN:
  7995. case GGML_OP_ARGMAX:
  7996. {
  7997. const uint32_t nr = ggml_nrows(src0);
  7998. if (nr > 262144) {
  7999. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  8000. } else if (nr > 512) {
  8001. elements = { 512, CEIL_DIV(nr, 512), 1 };
  8002. } else {
  8003. elements = { nr, 1, 1 };
  8004. }
  8005. } break;
  8006. case GGML_OP_SOLVE_TRI:
  8007. {
  8008. uint32_t nr = (uint32_t)(ne02 * ne03);
  8009. if (nr > 262144) {
  8010. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  8011. } else if (nr > 512) {
  8012. elements = { 512, CEIL_DIV(nr, 512), 1 };
  8013. } else {
  8014. elements = { nr, 1, 1 };
  8015. }
  8016. }
  8017. break;
  8018. case GGML_OP_RMS_NORM:
  8019. if (ctx->do_add_rms_partials) {
  8020. // Run one element per thread, 128 threads per workgroup
  8021. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  8022. } else {
  8023. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  8024. }
  8025. break;
  8026. case GGML_OP_SUM:
  8027. // We use GGML_OP_SUM_ROWS with 1 row.
  8028. elements = { 1, 1, 1 };
  8029. break;
  8030. case GGML_OP_GROUP_NORM:
  8031. {
  8032. const uint32_t num_groups = dst->op_params[0];
  8033. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  8034. } break;
  8035. case GGML_OP_DIAG_MASK_INF:
  8036. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  8037. break;
  8038. case GGML_OP_ROPE:
  8039. case GGML_OP_ROPE_BACK:
  8040. {
  8041. uint32_t nrows = (uint32_t)ggml_nrows(src0);
  8042. uint32_t z = 1;
  8043. if (nrows > ctx->device->properties.limits.maxComputeWorkGroupCount[0]) {
  8044. z = CEIL_DIV(nrows, 32768);
  8045. nrows = 32768;
  8046. }
  8047. elements = { nrows, (uint32_t)ne00, z };
  8048. } break;
  8049. case GGML_OP_GET_ROWS:
  8050. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  8051. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8052. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8053. break;
  8054. case GGML_OP_ARGSORT:
  8055. GGML_ASSERT(0);
  8056. break;
  8057. case GGML_OP_IM2COL:
  8058. {
  8059. const bool is_2D = dst->op_params[6] == 1;
  8060. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8061. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8062. const uint32_t KW = src0->ne[0];
  8063. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8064. const uint32_t OW = dst->ne[1];
  8065. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  8066. elements = { OW * KW * KH, OH, batch * IC };
  8067. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8068. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8069. } break;
  8070. case GGML_OP_IM2COL_3D:
  8071. {
  8072. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  8073. const uint32_t N = ne13 / IC;
  8074. const uint32_t KD = ne02;
  8075. const uint32_t KH = ne01;
  8076. const uint32_t KW = ne00;
  8077. const uint32_t OD = dst->ne[3] / N;
  8078. const uint32_t OH = dst->ne[2];
  8079. const uint32_t OW = dst->ne[1];
  8080. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  8081. const uint32_t N_OD_OH = N*OD*OH;
  8082. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  8083. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8084. } break;
  8085. case GGML_OP_TIMESTEP_EMBEDDING:
  8086. {
  8087. const uint32_t dim = dst->op_params[0];
  8088. uint32_t half_ceil = (dim + 1) / 2;
  8089. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  8090. } break;
  8091. case GGML_OP_CONV_TRANSPOSE_1D:
  8092. {
  8093. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  8094. } break;
  8095. case GGML_OP_POOL_2D:
  8096. {
  8097. const uint32_t N = dst->ne[3];
  8098. const uint32_t OC = dst->ne[2];
  8099. const uint32_t OH = dst->ne[1];
  8100. const uint32_t OW = dst->ne[0];
  8101. elements = { N * OC * OH * OW, 1, 1};
  8102. } break;
  8103. case GGML_OP_CONV_2D:
  8104. case GGML_OP_CONV_TRANSPOSE_2D:
  8105. if constexpr (std::is_same_v<PC, vk_op_conv2d_push_constants>) {
  8106. const uint32_t NPQ = pc.N * pc.OH * pc.OW;
  8107. const vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, pc.Cout, NPQ);
  8108. const uint32_t NPQ_blocks = CEIL_DIV(NPQ, vk_conv_block_sizes[shape].NPQ);
  8109. elements = { pc.Cout, NPQ_blocks, 1 };
  8110. if (elements[1] > 512) {
  8111. elements[2] = CEIL_DIV(elements[1], 512);
  8112. elements[1] = 512;
  8113. }
  8114. } else {
  8115. GGML_ABORT("invalid push constant type for CONV_2D");
  8116. }
  8117. break;
  8118. case GGML_OP_ADD:
  8119. case GGML_OP_SUB:
  8120. case GGML_OP_DIV:
  8121. case GGML_OP_MUL:
  8122. case GGML_OP_ADD1:
  8123. case GGML_OP_ARANGE:
  8124. case GGML_OP_FILL:
  8125. case GGML_OP_SCALE:
  8126. case GGML_OP_SQR:
  8127. case GGML_OP_SQRT:
  8128. case GGML_OP_SIN:
  8129. case GGML_OP_COS:
  8130. case GGML_OP_LOG:
  8131. case GGML_OP_TRI:
  8132. case GGML_OP_DIAG:
  8133. case GGML_OP_CLAMP:
  8134. case GGML_OP_PAD:
  8135. case GGML_OP_ROLL:
  8136. case GGML_OP_REPEAT:
  8137. case GGML_OP_REPEAT_BACK:
  8138. case GGML_OP_CPY:
  8139. case GGML_OP_CONCAT:
  8140. case GGML_OP_UPSCALE:
  8141. case GGML_OP_UNARY:
  8142. case GGML_OP_GLU:
  8143. case GGML_OP_CONV_2D_DW:
  8144. {
  8145. uint32_t ne = ggml_nelements(dst);
  8146. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8147. // Convert from number of logical elements to 2- or 4-byte units.
  8148. ne /= ggml_blck_size(src0->type);
  8149. if ((ggml_type_size(src0->type) % 4) == 0) {
  8150. ne *= ggml_type_size(src0->type) / 4;
  8151. } else {
  8152. ne *= ggml_type_size(src0->type) / 2;
  8153. }
  8154. }
  8155. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  8156. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  8157. // So divide by block size here before splitting into 512x512 groups.
  8158. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8159. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  8160. }
  8161. if (ne > 262144) {
  8162. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8163. } else if (ne > 512) {
  8164. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8165. } else {
  8166. elements = { ne, 1, 1 };
  8167. }
  8168. if (pipeline == ctx->device->pipeline_cpy_transpose_32 ||
  8169. pipeline == ctx->device->pipeline_cpy_transpose_16) {
  8170. // 32x32 tiles
  8171. elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32);
  8172. elements[1] = (uint32_t)CEIL_DIV(dst->ne[1], 32);
  8173. elements[2] = (uint32_t)(dst->ne[2]*dst->ne[3]);
  8174. elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]);
  8175. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8176. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8177. }
  8178. } break;
  8179. case GGML_OP_ADD_ID:
  8180. {
  8181. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  8182. } break;
  8183. case GGML_OP_SET_ROWS:
  8184. {
  8185. uint32_t ne = ggml_nelements(src0);
  8186. if (ggml_is_quantized(dst->type)) {
  8187. // quants run 32 threads each doing QUANT_K elements
  8188. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  8189. } else {
  8190. // scalar types do one element per thread, running 512 threads
  8191. ne = CEIL_DIV(ne, 512);
  8192. }
  8193. if (ne > 262144) {
  8194. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8195. } else if (ne > 512) {
  8196. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8197. } else {
  8198. elements = { ne, 1, 1 };
  8199. }
  8200. }
  8201. break;
  8202. case GGML_OP_SSM_CONV:
  8203. {
  8204. const uint32_t nr = src0->ne[1];
  8205. const uint32_t n_t = dst->ne[1];
  8206. const uint32_t n_s = dst->ne[2];
  8207. elements = { nr, n_t, n_s };
  8208. }
  8209. break;
  8210. default:
  8211. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  8212. break;
  8213. }
  8214. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  8215. vk_subbuffer a_buf = src0_buf;
  8216. if (ctx->do_add_rms_partials) {
  8217. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  8218. }
  8219. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8220. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  8221. } else if (op == GGML_OP_GLU) {
  8222. // Empty src1 is possible in glu, but the shader needs a buffer
  8223. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  8224. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  8225. } else if (op == GGML_OP_SOFT_MAX) {
  8226. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  8227. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  8228. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  8229. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  8230. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  8231. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  8232. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  8233. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  8234. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  8235. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  8236. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  8237. // buffer device address path doesn't use dst buffer
  8238. dst_buf.size = 1;
  8239. }
  8240. // im2col uses only src1 and dst buffers
  8241. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  8242. } else if (op == GGML_OP_COUNT_EQUAL) {
  8243. // count_equal assumes that destination buffer is initialized with zeroes
  8244. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  8245. ggml_vk_sync_buffers(ctx, subctx);
  8246. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  8247. } else if (op == GGML_OP_OPT_STEP_SGD) {
  8248. // OPT_STEP_SGD works on src0, it does not need dst
  8249. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  8250. } else if (use_src3) {
  8251. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  8252. } else if (use_src2) {
  8253. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  8254. } else if (use_src1) {
  8255. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  8256. } else {
  8257. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  8258. }
  8259. }
  8260. 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) {
  8261. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8262. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8263. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8264. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  8265. (uint32_t)ggml_nelements(src0),
  8266. (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,
  8267. (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,
  8268. (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,
  8269. 0,
  8270. 0.0f, 0.0f, 0,
  8271. });
  8272. }
  8273. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8274. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8275. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8276. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8277. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  8278. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  8279. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  8280. int offset = dst->op_params[3] / 4; // offset in bytes
  8281. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  8282. (uint32_t)ggml_nelements(src0),
  8283. (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,
  8284. (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,
  8285. (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,
  8286. 0,
  8287. 0.0f, 0.0f, offset,
  8288. });
  8289. }
  8290. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8291. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  8292. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  8293. // Make a list of all the tensors used by the op.
  8294. // Last element of the list is the dest tensor.
  8295. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  8296. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  8297. uint32_t num_tensors = num_srcs + 1;
  8298. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  8299. tensors[0] = first_node->src[0];
  8300. tensors[1] = first_node->src[1];
  8301. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  8302. // check whether the previous result is src[0] or src[1]
  8303. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  8304. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  8305. } else {
  8306. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  8307. }
  8308. }
  8309. tensors[num_srcs] = dst;
  8310. vk_op_multi_add_push_constants pc;
  8311. pc.ne20 = (uint32_t)dst->ne[0];
  8312. pc.ne21 = (uint32_t)dst->ne[1];
  8313. pc.ne22 = (uint32_t)dst->ne[2];
  8314. pc.ne23 = (uint32_t)dst->ne[3];
  8315. for (uint32_t i = 0; i < num_tensors; ++i) {
  8316. const ggml_tensor *t = tensors[i];
  8317. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  8318. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  8319. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  8320. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  8321. }
  8322. pc.rms_partials = ctx->do_add_rms_partials;
  8323. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  8324. if (pipeline == nullptr) {
  8325. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  8326. GGML_ABORT("fatal error");
  8327. }
  8328. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8329. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  8330. vk_buffer buf[MAX_PARAMETER_COUNT];
  8331. size_t offset[MAX_PARAMETER_COUNT];
  8332. bool uma[MAX_PARAMETER_COUNT];
  8333. for (uint32_t i = 0; i < num_tensors; ++i) {
  8334. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8335. buf[i] = nullptr;
  8336. offset[i] = 0;
  8337. uma[i] = false;
  8338. if (ctx->device->uma) {
  8339. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8340. uma[i] = buf[i] != nullptr;
  8341. }
  8342. if (!uma[i]) {
  8343. buf[i] = buf_ctx[i]->dev_buffer;
  8344. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8345. }
  8346. GGML_ASSERT(buf[i] != nullptr);
  8347. }
  8348. // If any remaining descriptors are unused, just point them at src[0]
  8349. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  8350. buf[i] = buf[0];
  8351. offset[i] = 0;
  8352. }
  8353. if (ctx->do_add_rms_partials) {
  8354. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  8355. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  8356. }
  8357. std::array<uint32_t, 3> elements;
  8358. uint32_t ne = ggml_nelements(dst);
  8359. if (ne > 262144) {
  8360. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8361. } else if (ne > 512) {
  8362. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8363. } else {
  8364. elements = { ne, 1, 1 };
  8365. }
  8366. static_assert(MAX_PARAMETER_COUNT == 12);
  8367. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8368. {
  8369. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8370. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8371. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8372. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8373. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8374. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8375. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8376. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  8377. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  8378. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  8379. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  8380. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  8381. }, pc, elements);
  8382. }
  8383. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8384. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8385. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8386. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8387. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  8388. (uint32_t)ggml_nelements(src0),
  8389. (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,
  8390. (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,
  8391. (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,
  8392. 0,
  8393. 0.0f, 0.0f, ctx->do_add_rms_partials,
  8394. });
  8395. }
  8396. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8397. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8398. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8399. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8400. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  8401. (uint32_t)ggml_nelements(src0),
  8402. (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,
  8403. (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,
  8404. (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,
  8405. 0,
  8406. 0.0f, 0.0f, 0,
  8407. });
  8408. }
  8409. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8410. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8411. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8412. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8413. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  8414. (uint32_t)ggml_nelements(src0),
  8415. (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,
  8416. (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,
  8417. (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,
  8418. 0,
  8419. 0.0f, 0.0f, 0,
  8420. });
  8421. }
  8422. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8423. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8424. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8425. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8426. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  8427. (uint32_t)ggml_nelements(src0),
  8428. (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,
  8429. (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,
  8430. (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,
  8431. 0,
  8432. 0.0f, 0.0f, 0,
  8433. });
  8434. }
  8435. static void ggml_vk_add_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  8436. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8437. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8438. const uint32_t src2_type_size = ggml_type_size(src2->type);
  8439. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  8440. (uint32_t)dst->ne[0],
  8441. (uint32_t)dst->ne[1],
  8442. (uint32_t)src0->nb[1] / src0_type_size,
  8443. (uint32_t)src0->nb[2] / src0_type_size,
  8444. (uint32_t)src1->nb[1] / src1_type_size,
  8445. (uint32_t)src2->nb[1] / src2_type_size,
  8446. });
  8447. }
  8448. static void ggml_vk_op_f32_wkv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_rwkv_wkv6_push_constants&& pc, int version) {
  8449. GGML_ASSERT(version == 6 || version == 7);
  8450. int num_srcs = version == 6 ? 6 : 7;
  8451. for (int i = 0; i < num_srcs; i++) {
  8452. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  8453. }
  8454. GGML_ASSERT(dst->buffer != nullptr);
  8455. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8456. GGML_ASSERT(pipeline != nullptr);
  8457. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8458. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8459. vk_subbuffer src_buf[7] = {};
  8460. for (int i = 0; i < num_srcs; i++) {
  8461. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8462. }
  8463. std::array<uint32_t, 3> elements = {
  8464. (uint32_t)(pc.B * pc.H),
  8465. 1,
  8466. 1
  8467. };
  8468. if (version == 6) {
  8469. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8470. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  8471. pc, elements);
  8472. } else if (version == 7) {
  8473. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8474. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8475. pc, elements);
  8476. } else {
  8477. // shouldn't happen
  8478. GGML_ASSERT(false);
  8479. }
  8480. }
  8481. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8482. const size_t seq_length = dst->src[0]->ne[2];
  8483. const size_t n_embed = dst->ne[0];
  8484. const size_t n_heads = dst->src[0]->ne[1];
  8485. const size_t n_seqs = dst->src[5]->ne[1];
  8486. ggml_vk_op_f32_wkv(
  8487. ctx, subctx, dst,
  8488. {
  8489. (uint32_t)n_seqs,
  8490. (uint32_t)seq_length,
  8491. (uint32_t)n_embed,
  8492. (uint32_t)n_heads,
  8493. },
  8494. 6
  8495. );
  8496. }
  8497. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8498. const size_t seq_length = dst->src[0]->ne[2];
  8499. const size_t n_embed = dst->ne[0];
  8500. const size_t n_heads = dst->src[0]->ne[1];
  8501. const size_t n_seqs = dst->src[6]->ne[1];
  8502. ggml_vk_op_f32_wkv(
  8503. ctx, subctx, dst,
  8504. {
  8505. (uint32_t)n_seqs,
  8506. (uint32_t)seq_length,
  8507. (uint32_t)n_embed,
  8508. (uint32_t)n_heads,
  8509. },
  8510. 7
  8511. );
  8512. }
  8513. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8514. const ggml_tensor * src0 = dst->src[0];
  8515. const ggml_tensor * src1 = dst->src[1];
  8516. const ggml_tensor * src2 = dst->src[2];
  8517. const ggml_tensor * src3 = dst->src[3];
  8518. const ggml_tensor * src4 = dst->src[4];
  8519. const ggml_tensor * src5 = dst->src[5];
  8520. GGML_ASSERT(dst->buffer != nullptr);
  8521. const uint32_t head_dim = src0->ne[1];
  8522. const uint32_t n_head = src1->ne[1];
  8523. const uint32_t n_group = src4->ne[1];
  8524. const uint32_t n_tok = src1->ne[2];
  8525. const uint32_t n_seq = src1->ne[3];
  8526. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8527. GGML_ASSERT(is_mamba2);
  8528. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8529. GGML_ASSERT(pipeline != nullptr);
  8530. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8531. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8532. const vk_op_ssm_scan_push_constants pc = {
  8533. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8534. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8535. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8536. (uint32_t)src3->nb[1],
  8537. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8538. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8539. (uint32_t)s_off,
  8540. n_head, head_dim, n_group, n_tok
  8541. };
  8542. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8543. vk_subbuffer src_buf[7] = {};
  8544. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8545. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8546. }
  8547. std::array<uint32_t, 3> elements;
  8548. const uint32_t d_state = src0->ne[0];
  8549. uint32_t num_subgroups = d_state / ctx->device->subgroup_size;
  8550. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups);
  8551. const uint32_t num_workgroups_y = n_seq;
  8552. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8553. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8554. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8555. pc, elements);
  8556. }
  8557. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8558. const ggml_tensor * src0 = dst->src[0];
  8559. const ggml_tensor * src1 = dst->src[1];
  8560. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8561. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8562. (uint32_t)src1->nb[1],
  8563. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8564. (uint32_t)src1->ne[0],
  8565. (uint32_t)src0->ne[0],
  8566. (uint32_t)src0->ne[1],
  8567. (uint32_t)dst->ne[1],
  8568. (uint32_t)dst->ne[2],
  8569. });
  8570. }
  8571. static void ggml_vk_op_f32_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_push_constants&& pc) {
  8572. const ggml_tensor * x = dst->src[0];
  8573. const ggml_tensor * g = dst->src[1];
  8574. const ggml_tensor * gm = dst->src[2];
  8575. const ggml_tensor * gv = dst->src[3];
  8576. const ggml_tensor * p = dst->src[4];
  8577. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8578. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8579. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8580. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8581. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8582. GGML_ASSERT(dst->buffer != nullptr);
  8583. GGML_ASSERT(ggml_is_contiguous(x));
  8584. GGML_ASSERT(ggml_is_contiguous(g));
  8585. GGML_ASSERT(ggml_is_contiguous(gm));
  8586. GGML_ASSERT(ggml_is_contiguous(gv));
  8587. GGML_ASSERT(ggml_is_contiguous(p));
  8588. GGML_ASSERT(ggml_are_same_shape(x, g));
  8589. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8590. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8591. GGML_ASSERT(ggml_nelements(p) == 7);
  8592. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8593. GGML_ASSERT(pipeline != nullptr);
  8594. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8595. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8596. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8597. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8598. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8599. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8600. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8601. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8602. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8603. pc, elements);
  8604. }
  8605. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8606. const size_t n = ggml_nelements(dst->src[0]);
  8607. ggml_vk_op_f32_opt_step_adamw(
  8608. ctx, subctx, dst,
  8609. { (uint32_t)n, 0, 0.0f, 0.0f, 0.0f, 0.0f }
  8610. );
  8611. }
  8612. static void ggml_vk_opt_step_sgd(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  8613. const size_t n = ggml_nelements(dst->src[0]);
  8614. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_OPT_STEP_SGD, { (uint32_t)n, 0, 0.0f, 0.0f, 0.0f, 0.0f });
  8615. }
  8616. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8617. int * op_params = (int *)dst->op_params;
  8618. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8619. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8620. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8621. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8622. (uint32_t)ggml_nelements(dst),
  8623. (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,
  8624. (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,
  8625. (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,
  8626. 0,
  8627. 0.0f, 0.0f, op_params[0],
  8628. });
  8629. }
  8630. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8631. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8632. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8633. GGML_TENSOR_UNARY_OP_LOCALS
  8634. float sf0 = (float)ne0 / ne00;
  8635. float sf1 = (float)ne1 / ne01;
  8636. float sf2 = (float)ne2 / ne02;
  8637. float sf3 = (float)ne3 / ne03;
  8638. float pixel_offset = 0.5f;
  8639. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8640. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8641. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8642. pixel_offset = 0.0f;
  8643. }
  8644. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8645. (uint32_t)ggml_nelements(dst), 0, 0,
  8646. (uint32_t)ne00, (uint32_t)ne01,
  8647. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8648. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8649. sf0, sf1, sf2, sf3, pixel_offset
  8650. });
  8651. }
  8652. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8653. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8654. p.param1 = ggml_get_op_params_f32(dst, 0);
  8655. p.param2 = ggml_get_op_params_f32(dst, 1);
  8656. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8657. }
  8658. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8659. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8660. }
  8661. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8662. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8663. }
  8664. static void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8665. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8666. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8667. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8668. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, {
  8669. (uint32_t)ggml_nelements(src0),
  8670. (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,
  8671. (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,
  8672. (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,
  8673. 0,
  8674. 0.0f, 0.0f, 0,
  8675. });
  8676. }
  8677. static void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8678. VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8679. vk_op_push_constants pc = {
  8680. (uint32_t)ggml_nelements(dst),
  8681. 1,
  8682. ggml_get_op_params_f32(dst, 0),
  8683. ggml_get_op_params_f32(dst, 2),
  8684. 0.0f, 0.0f,
  8685. };
  8686. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_ARANGE);
  8687. GGML_ASSERT(pipeline != nullptr);
  8688. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8689. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8690. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8691. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8692. }
  8693. static void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8694. VK_LOG_DEBUG("ggml_vk_fill(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8695. vk_op_push_constants pc = {
  8696. (uint32_t)ggml_nelements(dst),
  8697. 1,
  8698. ggml_get_op_params_f32(dst, 0),
  8699. 0.0f,
  8700. 0.0f, 0.0f,
  8701. };
  8702. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_FILL);
  8703. GGML_ASSERT(pipeline != nullptr);
  8704. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8705. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8706. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8707. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8708. }
  8709. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8710. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8711. }
  8712. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8713. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8714. }
  8715. static void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8716. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst));
  8717. }
  8718. static void ggml_vk_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8719. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8720. p.param1 = ggml_get_op_params_f32(dst, 0);
  8721. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TRI, std::move(p));
  8722. }
  8723. static void ggml_vk_diag(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8724. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8725. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG, std::move(p));
  8726. }
  8727. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8728. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8729. p.param1 = ggml_get_op_params_f32(dst, 0);
  8730. p.param2 = ggml_get_op_params_f32(dst, 1);
  8731. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8732. }
  8733. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8734. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8735. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8736. }
  8737. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8738. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8739. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8740. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8741. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8742. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8743. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8744. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8745. memcpy(&p.param1, &s01_packed, sizeof(float));
  8746. memcpy(&p.param2, &s23_packed, sizeof(float));
  8747. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8748. }
  8749. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8750. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8751. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8752. }
  8753. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8754. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8755. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8756. }
  8757. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8758. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8759. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8760. // Convert from number of logical elements to 2- or 4-byte units.
  8761. ne /= ggml_blck_size(src0->type);
  8762. if ((ggml_type_size(src0->type) % 4) == 0) {
  8763. ne *= ggml_type_size(src0->type) / 4;
  8764. } else {
  8765. ne *= ggml_type_size(src0->type) / 2;
  8766. }
  8767. }
  8768. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8769. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8770. }
  8771. static void ggml_vk_set_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8772. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8773. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8774. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8775. // Skip empty skip_rows operations. For most ops the empty check at the start
  8776. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8777. // with empty srcs.
  8778. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8779. return;
  8780. }
  8781. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8782. (uint32_t)ggml_nelements(src0),
  8783. (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,
  8784. (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,
  8785. (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,
  8786. 0,
  8787. 0.0f, 0.0f, 0,
  8788. });
  8789. }
  8790. static void ggml_vk_silu_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8791. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SILU_BACK, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f, 0.0f, 0.0f });
  8792. }
  8793. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8794. float * op_params = (float *)dst->op_params;
  8795. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f, 0.0f, 0.0f });
  8796. }
  8797. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8798. const int * int_op_params = (const int *)dst->op_params;
  8799. const float * float_op_params = (const float *)dst->op_params;
  8800. const uint32_t num_groups = int_op_params[0];
  8801. const float eps = float_op_params[1];
  8802. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8803. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f, 0.0f, 0.0f });
  8804. }
  8805. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8806. const uint32_t ne = (uint32_t)node->ne[0];
  8807. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8808. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8809. return num_partials;
  8810. }
  8811. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8812. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8813. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8814. return num_bytes;
  8815. }
  8816. static vk_op_rope_push_constants ggml_vk_make_rope_constants(const ggml_tensor *dst, const ggml_tensor *src0, const bool has_ff, bool backprop, const uint32_t set_rows_stride) {
  8817. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8818. const int mode = ((const int32_t *) dst->op_params)[2];
  8819. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8820. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8821. const float freq_base = ((const float *) dst->op_params)[5];
  8822. const float freq_scale = ((const float *) dst->op_params)[6];
  8823. const float ext_factor = ((const float *) dst->op_params)[7];
  8824. const float attn_factor = ((const float *) dst->op_params)[8];
  8825. const float beta_fast = ((const float *) dst->op_params)[9];
  8826. const float beta_slow = ((const float *) dst->op_params)[10];
  8827. int sections[4] {};
  8828. if (mode & GGML_ROPE_TYPE_MROPE) {
  8829. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8830. }
  8831. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8832. float corr_dims[2];
  8833. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8834. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8835. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8836. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8837. vk_op_rope_push_constants rope {
  8838. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8839. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8840. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8841. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8842. };
  8843. return rope;
  8844. }
  8845. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, float * op_params) {
  8846. ggml_tensor * dst;
  8847. const ggml_tensor * src0;
  8848. const ggml_tensor * src1;
  8849. if (ctx->num_additional_fused_ops > 0) {
  8850. // fused rms_norm + mul
  8851. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8852. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8853. dst = mul;
  8854. src0 = cgraph->nodes[node_idx]->src[0];
  8855. src1 = other_src;
  8856. } else {
  8857. dst = cgraph->nodes[node_idx];
  8858. src0 = src1 = dst->src[0];
  8859. }
  8860. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8861. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8862. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8863. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8864. vk_op_binary_push_constants bin {
  8865. (uint32_t)ggml_nelements(src0),
  8866. (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,
  8867. (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,
  8868. (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,
  8869. 0,
  8870. op_params[0], 0.0f, (int32_t)param3,
  8871. };
  8872. // more than one fused op means rms_norm+mul+rope
  8873. if (ctx->num_additional_fused_ops > 1) {
  8874. static constexpr uint32_t max_tensors = 7;
  8875. const ggml_tensor *tensors[max_tensors] {};
  8876. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8877. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8878. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8879. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8880. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8881. tensors[0] = rms->src[0];
  8882. tensors[1] = other_src;
  8883. tensors[2] = mul;
  8884. tensors[3] = rope->src[1]; // pos
  8885. tensors[4] = rope->src[2]; // ff
  8886. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8887. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8888. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8889. vk_op_rms_norm_mul_rope_push_constants pc;
  8890. pc.bin = bin;
  8891. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8892. vk_pipeline pipeline = tensors[5]->type == GGML_TYPE_F16 ? ctx->device->pipeline_rms_norm_mul_rope_f32_f16 : ctx->device->pipeline_rms_norm_mul_rope_f32_f32;
  8893. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8894. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8895. vk_buffer buf[max_tensors];
  8896. size_t offset[max_tensors];
  8897. bool uma[max_tensors];
  8898. for (uint32_t i = 0; i < max_tensors; ++i) {
  8899. if (!tensors[i]) {
  8900. // If any remaining descriptors are unused, just point them at src[0]
  8901. buf[i] = buf[0];
  8902. offset[i] = 0;
  8903. continue;
  8904. }
  8905. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8906. buf[i] = nullptr;
  8907. offset[i] = 0;
  8908. uma[i] = false;
  8909. if (ctx->device->uma) {
  8910. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8911. uma[i] = buf[i] != nullptr;
  8912. }
  8913. if (!uma[i]) {
  8914. buf[i] = buf_ctx[i]->dev_buffer;
  8915. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8916. }
  8917. GGML_ASSERT(buf[i] != nullptr);
  8918. }
  8919. std::array<uint32_t, 3> elements;
  8920. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8921. static_assert(max_tensors == 7);
  8922. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8923. {
  8924. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8925. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8926. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8927. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8928. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8929. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8930. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8931. }, pc, elements);
  8932. } else {
  8933. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8934. }
  8935. if (ctx->do_add_rms_partials_offset_calculation) {
  8936. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8937. ctx->do_add_rms_partials = false;
  8938. ctx->do_add_rms_partials_offset_calculation = false;
  8939. }
  8940. }
  8941. static void ggml_vk_rms_norm_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8942. float * op_params = (float *)dst->op_params;
  8943. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM_BACK, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f, 0.0f, 0.0f });
  8944. }
  8945. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8946. float * op_params = (float *)dst->op_params;
  8947. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_L2_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f, 0.0f, 0.0f });
  8948. }
  8949. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8950. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f, 0.0f, 0.0f });
  8951. }
  8952. static void ggml_vk_xielu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8953. float * op_params = (float *)dst->op_params;
  8954. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY,
  8955. {
  8956. (uint32_t)ggml_nelements(src0), 0,
  8957. op_params[1], op_params[2], op_params[3], op_params[4]
  8958. }
  8959. );
  8960. }
  8961. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8962. const float * op_params_f = (const float *)dst->op_params;
  8963. const bool swapped = (bool)dst->op_params[1];
  8964. const bool split = src1 != nullptr;
  8965. const float alpha = op_params_f[2];
  8966. const float limit = op_params_f[3];
  8967. GGML_ASSERT(ggml_is_contiguous(src0));
  8968. if (!split) {
  8969. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8970. } else {
  8971. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8972. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8973. GGML_ASSERT(src0->type == src1->type);
  8974. }
  8975. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8976. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8977. {
  8978. (uint32_t)ggml_nelements(dst),
  8979. (uint32_t)src0->ne[0],
  8980. (uint32_t)dst->ne[0],
  8981. mode,
  8982. alpha,
  8983. limit
  8984. });
  8985. }
  8986. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8987. int32_t * op_params = (int32_t *)dst->op_params;
  8988. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] });
  8989. }
  8990. static void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  8991. float * op_params = (float *)dst->op_params;
  8992. float scale = op_params[0];
  8993. float max_bias = op_params[1];
  8994. const uint32_t ncols = (uint32_t)src0->ne[0];
  8995. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8996. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8997. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8998. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8999. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  9000. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  9001. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  9002. const uint32_t n_head_kv = src0->ne[2];
  9003. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  9004. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  9005. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  9006. vk_op_soft_max_push_constants pc {
  9007. ncols,
  9008. src1 != nullptr ? nrows_y : (uint32_t)0,
  9009. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  9010. ne12, ne13,
  9011. nb11, nb12, nb13,
  9012. scale, max_bias,
  9013. m0, m1,
  9014. n_head_log2,
  9015. nrows_x,
  9016. src2 != nullptr
  9017. };
  9018. if (ncols <= 16384) {
  9019. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, std::move(pc));
  9020. } else {
  9021. vk_subbuffer buf_a = ggml_vk_tensor_subbuffer(ctx, src0);
  9022. vk_subbuffer buf_b = src1 ? ggml_vk_tensor_subbuffer(ctx, src1) : buf_a;
  9023. vk_subbuffer buf_c = src2 ? ggml_vk_tensor_subbuffer(ctx, src2) : buf_a;
  9024. vk_subbuffer buf_d = ggml_vk_tensor_subbuffer(ctx, dst);
  9025. uint32_t elems_per_wg = 128 * 4;
  9026. uint32_t num_wgs = CEIL_DIV(ncols, elems_per_wg);
  9027. size_t tmp_size = num_wgs * nrows_x * sizeof(float);
  9028. if (ctx->prealloc_size_x < tmp_size) {
  9029. ctx->prealloc_size_x = tmp_size;
  9030. ggml_vk_preallocate_buffers(ctx, subctx);
  9031. }
  9032. if (ctx->prealloc_size_y < tmp_size) {
  9033. ctx->prealloc_size_y = tmp_size;
  9034. ggml_vk_preallocate_buffers(ctx, subctx);
  9035. }
  9036. if (ctx->prealloc_x_need_sync || ctx->prealloc_y_need_sync) {
  9037. ggml_vk_sync_buffers(ctx, subctx);
  9038. }
  9039. vk_subbuffer buf_x = { ctx->prealloc_x, 0, tmp_size };
  9040. vk_subbuffer buf_y = { ctx->prealloc_y, 0, tmp_size };
  9041. std::array<uint32_t, 3> elements = { num_wgs, nrows_x, 1 };
  9042. vk_pipeline pipeline1 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large1_f32_f16 : ctx->device->pipeline_soft_max_large1_f32;
  9043. vk_pipeline pipeline2 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large2_f32_f16 : ctx->device->pipeline_soft_max_large2_f32;
  9044. vk_pipeline pipeline3 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large3_f32_f16 : ctx->device->pipeline_soft_max_large3_f32;
  9045. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  9046. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  9047. ggml_pipeline_request_descriptor_sets(ctx, pipeline3, 1);
  9048. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9049. ggml_vk_sync_buffers(ctx, subctx);
  9050. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9051. ggml_vk_sync_buffers(ctx, subctx);
  9052. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline3, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9053. ctx->prealloc_x_need_sync = true;
  9054. ctx->prealloc_y_need_sync = true;
  9055. }
  9056. }
  9057. static void ggml_vk_soft_max_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9058. float * op_params = (float *)dst->op_params;
  9059. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOFT_MAX_BACK, { (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), op_params[0], op_params[1], 0.0f, 0.0f });
  9060. }
  9061. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  9062. topk_moe_mode mode = ctx->fused_topk_moe_mode;
  9063. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  9064. ggml_tensor * bias = (mode == TOPK_MOE_SIGMOID_NORM_BIAS) ? cgraph->nodes[node_idx + 2]->src[1] : logits;
  9065. ggml_tensor * weights = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  9066. ggml_tensor * ids = (mode == TOPK_MOE_SIGMOID_NORM_BIAS) ? cgraph->nodes[node_idx + 4] :
  9067. (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] :
  9068. cgraph->nodes[node_idx + 3];
  9069. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  9070. GGML_ASSERT(bias->type == GGML_TYPE_F32);
  9071. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  9072. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  9073. const int n_experts = logits->ne[0];
  9074. const int n_rows = logits->ne[1];
  9075. const int n_expert_used = weights->ne[1];
  9076. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  9077. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  9078. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9079. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  9080. vk_subbuffer bias_buf = ggml_vk_tensor_subbuffer(ctx, bias);
  9081. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  9082. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  9083. vk_op_topk_moe_push_constants pc {};
  9084. pc.n_rows = n_rows;
  9085. pc.n_experts_push = n_experts;
  9086. pc.n_expert_used = n_expert_used;
  9087. pc.clamp_min = -std::numeric_limits<float>::infinity();
  9088. pc.clamp_max = std::numeric_limits<float>::infinity();
  9089. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  9090. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  9091. GGML_ASSERT(clamp->op == GGML_OP_CLAMP);
  9092. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  9093. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  9094. }
  9095. if (mode == TOPK_MOE_SIGMOID_NORM_BIAS) {
  9096. ggml_tensor * clamp = cgraph->nodes[node_idx + 8];
  9097. GGML_ASSERT(clamp->op == GGML_OP_CLAMP);
  9098. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  9099. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  9100. }
  9101. #define GATING_FUNC_SOFTMAX 0
  9102. #define GATING_FUNC_SIGMOID 1
  9103. #define GATING_FUNC_SOFTMAX_WEIGHT 2
  9104. pc.gating_func = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? GATING_FUNC_SIGMOID :
  9105. mode == TOPK_MOE_LATE_SOFTMAX ? GATING_FUNC_SOFTMAX_WEIGHT :
  9106. GATING_FUNC_SOFTMAX;
  9107. pc.has_bias = mode == TOPK_MOE_SIGMOID_NORM_BIAS;
  9108. pc.with_norm = mode == TOPK_MOE_EARLY_SOFTMAX_NORM || mode == TOPK_MOE_SIGMOID_NORM_BIAS;
  9109. if (ctx->fused_topk_moe_scale) {
  9110. GGML_ASSERT(weights->op == GGML_OP_SCALE);
  9111. pc.output_scale = ggml_get_op_params_f32(weights, 0);
  9112. pc.output_bias = ggml_get_op_params_f32(weights, 1);
  9113. } else {
  9114. pc.output_scale = 1.0f;
  9115. pc.output_bias = 0.0f;
  9116. }
  9117. GGML_ASSERT(n_expert_used <= n_experts);
  9118. const uint32_t rows_per_block = 4;
  9119. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  9120. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, bias_buf, weights_buf, ids_buf}, pc, elements);
  9121. }
  9122. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  9123. ggml_tensor * dst = cgraph->nodes[node_idx];
  9124. const ggml_tensor * src0 = dst->src[0];
  9125. const ggml_tensor * src1 = dst->src[1];
  9126. const ggml_tensor * src2 = dst->src[2];
  9127. const ggml_tensor * src3 = nullptr;
  9128. const int n_dims = ((int32_t *) dst->op_params)[1];
  9129. const int mode = ((int32_t *) dst->op_params)[2];
  9130. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  9131. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  9132. const float freq_base = ((float *) dst->op_params)[5];
  9133. const float beta_fast = ((float *) dst->op_params)[9];
  9134. const float beta_slow = ((float *) dst->op_params)[10];
  9135. int sections[4] {};
  9136. if (mode & GGML_ROPE_TYPE_MROPE) {
  9137. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  9138. }
  9139. float corr_dims[2];
  9140. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  9141. uint32_t set_rows_stride = 0;
  9142. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  9143. // and overrides the dst and sets src3=row_indices
  9144. if (ctx->num_additional_fused_ops > 0) {
  9145. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  9146. src3 = cgraph->nodes[node_idx + 2]->src[1];
  9147. dst = cgraph->nodes[node_idx + 2];
  9148. }
  9149. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  9150. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  9151. }
  9152. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9153. const uint32_t * op_params = (const uint32_t *)dst->op_params;
  9154. uint32_t ncols = src0->ne[0];
  9155. uint32_t nrows = ggml_nrows(src0);
  9156. uint32_t ncols_pad_log2 = (uint32_t)ceilf(log2f(float(ncols)));
  9157. uint32_t ncolsp2 = 1 << ncols_pad_log2;
  9158. vk_op_argsort_push_constants pc { ncols, ncolsp2, ncols_pad_log2, nrows, op_params[0], 0, 0, 0, 0, };
  9159. // Pick the largest workgroup size <= ncolsp2
  9160. uint32_t pipeline_idx = std::min(ncols_pad_log2, num_argsort_pipelines - 1);
  9161. // Use the "small" argsort shader if the whole sort can be done by a single workgroup.
  9162. bool use_small = ncols_pad_log2 <= ctx->device->max_workgroup_size_log2 &&
  9163. ctx->device->pipeline_argsort_f32[pipeline_idx] != nullptr;
  9164. vk_pipeline pipeline = use_small ? ctx->device->pipeline_argsort_f32[pipeline_idx]
  9165. : ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  9166. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9167. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9168. vk_subbuffer subbuf1 = dst_buf;
  9169. // Reserve space for ivec2 per element, with rows padded to a power of two
  9170. if (!use_small) {
  9171. const size_t x_sz = size_t{ncolsp2} * nrows * 2 * sizeof(int);
  9172. if (ctx->prealloc_size_x < x_sz) {
  9173. ctx->prealloc_size_x = x_sz;
  9174. ggml_vk_preallocate_buffers(ctx, subctx);
  9175. }
  9176. if (ctx->prealloc_x_need_sync) {
  9177. ggml_vk_sync_buffers(ctx, subctx);
  9178. }
  9179. subbuf1 = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  9180. }
  9181. std::array<uint32_t, 3> elements;
  9182. elements[0] = ncolsp2;
  9183. elements[1] = std::min((uint32_t)ggml_nrows(src0), ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  9184. elements[2] = 1;
  9185. // First dispatch initializes tmp_idx and does the first N passes where
  9186. // there is only communication between threads in the same workgroup.
  9187. {
  9188. vk_op_argsort_push_constants pc2 = pc;
  9189. pc2.outer_start = 0;
  9190. pc2.outer_end = std::min(ncols_pad_log2, ctx->device->max_workgroup_size_log2);
  9191. pc2.inner_start = 0;
  9192. pc2.inner_end = 100;
  9193. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9194. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  9195. }
  9196. if (!use_small) {
  9197. ggml_vk_sync_buffers(ctx, subctx);
  9198. // Loop over outer/inner passes, synchronizing between each pass.
  9199. for (uint32_t outer = ctx->device->max_workgroup_size_log2; outer < ncols_pad_log2; ++outer) {
  9200. for (uint32_t inner = 0; inner < outer + 1; ++inner) {
  9201. vk_op_argsort_push_constants pc2 = pc;
  9202. pc2.outer_start = outer;
  9203. pc2.outer_end = outer + 1;
  9204. pc2.inner_start = inner;
  9205. pc2.inner_end = inner + 1;
  9206. // When the inner idx is large enough, there's only communication
  9207. // within a workgroup. So the remaining inner iterations can all
  9208. // run in the same dispatch.
  9209. if (outer - inner < pipeline_idx) {
  9210. pc2.inner_end = 100;
  9211. inner = outer;
  9212. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  9213. } else {
  9214. // Smaller workgroup empirically seems to perform better
  9215. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx - 2];
  9216. }
  9217. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9218. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  9219. ggml_vk_sync_buffers(ctx, subctx);
  9220. }
  9221. }
  9222. ctx->prealloc_x_need_sync = true;
  9223. }
  9224. }
  9225. static void ggml_vk_topk(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9226. uint32_t ncols = src0->ne[0];
  9227. uint32_t nrows = ggml_nrows(src0);
  9228. uint32_t k = dst->ne[0];
  9229. vk_op_topk_push_constants pc { ncols, ncols, ncols, k, nrows, 0, 0 };
  9230. if (ctx->prealloc_x_need_sync) {
  9231. ggml_vk_sync_buffers(ctx, subctx);
  9232. }
  9233. std::array<uint32_t, 3> elements;
  9234. elements[1] = std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  9235. elements[2] = 1;
  9236. uint32_t num_elements = ncols;
  9237. // Each iteration reduces a workgroup's worth of elements down to the K
  9238. // largest elements. Repeat until we have the top K elements.
  9239. // Need to do at least one iteration to write out the results.
  9240. bool done_one_iter = false;
  9241. uint32_t dbl_buf_index = 0;
  9242. size_t dbl_buf_size;
  9243. while (num_elements > k || !done_one_iter) {
  9244. // Prefer going as small as num_topk_pipelines - 3 for perf reasons.
  9245. // But if K is larger, then we need a larger workgroup
  9246. uint32_t max_pipeline = num_topk_pipelines - 1;
  9247. uint32_t preferred_pipeline = std::max(num_topk_pipelines - 3, (uint32_t)log2f(float(k)) + 2);
  9248. max_pipeline = std::min(preferred_pipeline, max_pipeline);
  9249. uint32_t min_pipeline = (uint32_t)log2f(float(k)) + 1;
  9250. // require full subgroup
  9251. min_pipeline = std::max(min_pipeline, ctx->device->subgroup_size_log2);
  9252. uint32_t pipeline_idx = (uint32_t)ceilf(log2f(float(num_elements)));
  9253. pipeline_idx = std::min(pipeline_idx, max_pipeline);
  9254. pipeline_idx = std::max(pipeline_idx, min_pipeline);
  9255. if (num_elements > (1u << pipeline_idx)) {
  9256. // If we could finish on this loop iteration (i.e. a single workgroup)
  9257. // then do so. It's better than the overhead of another pass.
  9258. for (uint32_t i = pipeline_idx; i < num_topk_pipelines; ++i) {
  9259. if (num_elements <= (1u << i)) {
  9260. pipeline_idx = i;
  9261. break;
  9262. }
  9263. }
  9264. }
  9265. vk_pipeline pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  9266. // If the device doesn't support a pipeline this large, use smaller
  9267. while (!pipeline) {
  9268. pipeline_idx--;
  9269. GGML_ASSERT(pipeline_idx >= min_pipeline);
  9270. pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  9271. }
  9272. vk_op_topk_push_constants pc2 = pc;
  9273. pc2.ncols_input = num_elements;
  9274. // Number of elements remaining after this pass
  9275. uint32_t num_dst_elements = (num_elements / pipeline->wg_denoms[0]) * k + std::min(k, num_elements % pipeline->wg_denoms[0]);
  9276. pc2.ncols_output = num_dst_elements;
  9277. if (!done_one_iter) {
  9278. // Reserve space for ivec2 per element, double buffered
  9279. // K per workgroup per row
  9280. dbl_buf_size = num_dst_elements * nrows * 2 * sizeof(int);
  9281. dbl_buf_size = ROUNDUP_POW2(dbl_buf_size, ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  9282. const size_t x_sz = dbl_buf_size * 2;
  9283. if (ctx->prealloc_size_x < x_sz) {
  9284. ctx->prealloc_size_x = x_sz;
  9285. ggml_vk_preallocate_buffers(ctx, subctx);
  9286. }
  9287. }
  9288. vk_subbuffer src_buf;
  9289. vk_subbuffer dst_buf;
  9290. if (num_elements == ncols) {
  9291. pc2.first_pass = 1;
  9292. src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9293. } else {
  9294. src_buf = { ctx->prealloc_x, dbl_buf_index * dbl_buf_size, dbl_buf_size };
  9295. }
  9296. if (num_dst_elements == k) {
  9297. pc2.last_pass = 1;
  9298. dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9299. } else {
  9300. dst_buf = { ctx->prealloc_x, (dbl_buf_index ^ 1) * dbl_buf_size, dbl_buf_size };
  9301. }
  9302. elements[0] = num_elements;
  9303. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9304. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src_buf, dst_buf }, pc2, elements);
  9305. num_elements = num_dst_elements;
  9306. dbl_buf_index ^= 1;
  9307. if (num_elements > k) {
  9308. ggml_vk_sync_buffers(ctx, subctx);
  9309. }
  9310. done_one_iter = true;
  9311. }
  9312. ctx->prealloc_x_need_sync = true;
  9313. }
  9314. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9315. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  9316. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  9317. }
  9318. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9319. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9320. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  9321. }
  9322. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9323. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9324. p.weight = 1.0f / (float)src0->ne[0];
  9325. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  9326. }
  9327. static void ggml_vk_cumsum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9328. vk_op_sum_rows_push_constants pc = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9329. // Use the single pass shader when the rows are small or there are enough rows to fill the GPU.
  9330. // For fewer, larger rows, use the multipass shader to spread each row across SMs.
  9331. if (dst->ne[0] <= 4096 || ggml_nrows(dst) >= ctx->device->shader_core_count) {
  9332. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CUMSUM, pc);
  9333. return;
  9334. }
  9335. // First pass computes partial sums within a block, and stores the last partial
  9336. // to the temp buffer. Second pass sums the block partials from the temp buffer
  9337. // and adds that to the result of the first pass.
  9338. vk_pipeline pipeline1 = ctx->device->pipeline_cumsum_multipass1_f32;
  9339. vk_pipeline pipeline2 = ctx->device->pipeline_cumsum_multipass2_f32;
  9340. GGML_ASSERT(pipeline1 != nullptr && pipeline2 != nullptr);
  9341. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  9342. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  9343. std::array<uint32_t, 3> elements;
  9344. elements[0] = dst->ne[0];
  9345. elements[1] = (uint32_t)ggml_nrows(dst);
  9346. elements[2] = 1;
  9347. size_t temp_size = sizeof(float) * elements[0] * ggml_nrows(dst);
  9348. if (ctx->prealloc_size_split_k < temp_size) {
  9349. ctx->prealloc_size_split_k = temp_size;
  9350. ggml_vk_preallocate_buffers(ctx, subctx);
  9351. }
  9352. vk_subbuffer src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9353. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9354. vk_subbuffer temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  9355. if (ctx->prealloc_split_k_need_sync) {
  9356. ggml_vk_sync_buffers(ctx, subctx);
  9357. }
  9358. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, {src_buf, dst_buf, temp_buf}, pc, elements);
  9359. ggml_vk_sync_buffers(ctx, subctx);
  9360. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, {src_buf, dst_buf, temp_buf}, pc, elements);
  9361. ctx->prealloc_split_k_need_sync = true;
  9362. }
  9363. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9364. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGMAX, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f, 0.0f, 0.0f });
  9365. }
  9366. static void ggml_vk_count_equal(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9367. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_COUNT_EQUAL, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f, 0.0f, 0.0f });
  9368. }
  9369. static void ggml_vk_solve_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9370. const uint32_t src0_type_size = ggml_type_size(src0->type);
  9371. const uint32_t src1_type_size = ggml_type_size(src1->type);
  9372. const uint32_t dst_type_size = ggml_type_size(dst->type);
  9373. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOLVE_TRI, {
  9374. (uint32_t)ggml_nelements(src0),
  9375. (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,
  9376. (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,
  9377. (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,
  9378. 0,
  9379. 0.0f, 0.0f, 0,
  9380. });
  9381. }
  9382. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9383. const int32_t s0 = dst->op_params[0];
  9384. const int32_t s1 = dst->op_params[1];
  9385. const int32_t p0 = dst->op_params[2];
  9386. const int32_t p1 = dst->op_params[3];
  9387. const int32_t d0 = dst->op_params[4];
  9388. const int32_t d1 = dst->op_params[5];
  9389. const bool is_2D = dst->op_params[6] == 1;
  9390. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  9391. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  9392. const uint32_t IW = src1->ne[0];
  9393. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  9394. const uint32_t KW = src0->ne[0];
  9395. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  9396. const uint32_t OW = dst->ne[1];
  9397. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  9398. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  9399. const uint32_t pelements = OW * KW * KH;
  9400. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  9401. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9402. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9403. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9404. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  9405. dst_addr,
  9406. batch_offset, offset_delta,
  9407. IC, IW, IH, OW, OH, KW, KH,
  9408. pelements,
  9409. IC * KH * KW,
  9410. s0, s1, p0, p1, d0, d1, batch * IC
  9411. });
  9412. }
  9413. static void ggml_vk_im2col_3d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9414. GGML_TENSOR_BINARY_OP_LOCALS
  9415. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  9416. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  9417. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  9418. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  9419. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  9420. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  9421. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  9422. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  9423. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  9424. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  9425. const int64_t N = ne13 / IC;
  9426. const int64_t ID = ne12;
  9427. const int64_t IH = ne11;
  9428. const int64_t IW = ne10;
  9429. const int64_t KD = ne02;
  9430. const int64_t KH = ne01;
  9431. const int64_t KW = ne00;
  9432. const int64_t OD = ne3 / N;
  9433. const int64_t OH = ne2;
  9434. const int64_t OW = ne1;
  9435. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9436. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9437. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9438. vk_op_im2col_3d_push_constants pc {};
  9439. pc.dst_addr = dst_addr;
  9440. pc.nb10 = nb10 / ggml_type_size(src1->type);
  9441. pc.nb11 = nb11 / ggml_type_size(src1->type);
  9442. pc.nb12 = nb12 / ggml_type_size(src1->type);
  9443. pc.nb13 = nb13 / ggml_type_size(src1->type);
  9444. pc.s0 = s0;
  9445. pc.s1 = s1;
  9446. pc.s2 = s2;
  9447. pc.p0 = p0;
  9448. pc.p1 = p1;
  9449. pc.p2 = p2;
  9450. pc.d0 = d0;
  9451. pc.d1 = d1;
  9452. pc.d2 = d2;
  9453. pc.IW = IW;
  9454. pc.IH = IH;
  9455. pc.ID = ID;
  9456. pc.IC = IC;
  9457. pc.KW = KW;
  9458. pc.OH = OH;
  9459. pc.KD_KH_KW = KD*KH*KW;
  9460. pc.KH_KW = KH*KW;
  9461. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  9462. pc.N_OD_OH = N*OD*OH;
  9463. pc.OD_OH = OD*OH;
  9464. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  9465. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  9466. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  9467. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  9468. }
  9469. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9470. const uint32_t dim = dst->op_params[0];
  9471. const uint32_t max_period = dst->op_params[1];
  9472. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  9473. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  9474. nb1, dim, max_period,
  9475. });
  9476. }
  9477. static void ggml_vk_conv_transpose_1d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9478. // src0: (K, Cout, Cin, 1) -- kernel
  9479. // src1: (L, Cin, 1, 1) -- input
  9480. // dst: (*, Cout, 1, 1)
  9481. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  9482. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9483. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  9484. GGML_TENSOR_BINARY_OP_LOCALS
  9485. GGML_ASSERT(nb00 == sizeof(float));
  9486. GGML_ASSERT(nb10 == sizeof(float));
  9487. const int32_t s0 = dst->op_params[0];
  9488. vk_op_conv_transpose_1d_push_constants p{};
  9489. p.Cout = static_cast<uint32_t>(ne01);
  9490. p.Cin = static_cast<uint32_t>(ne02);
  9491. p.K = static_cast<uint32_t>(ne00);
  9492. p.L = static_cast<uint32_t>(ne10);
  9493. p.KL = static_cast<uint32_t>(ne0);
  9494. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9495. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9496. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9497. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9498. p.s0 = static_cast<uint32_t>(s0);
  9499. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  9500. }
  9501. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9502. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  9503. const int32_t k1 = dst->op_params[1];
  9504. const int32_t k0 = dst->op_params[2];
  9505. const int32_t s1 = dst->op_params[3];
  9506. const int32_t s0 = dst->op_params[4];
  9507. const int32_t p1 = dst->op_params[5];
  9508. const int32_t p0 = dst->op_params[6];
  9509. const uint32_t IH = src0->ne[1];
  9510. const uint32_t IW = src0->ne[0];
  9511. const uint32_t N = dst->ne[3];
  9512. const uint32_t OC = dst->ne[2];
  9513. const uint32_t OH = dst->ne[1];
  9514. const uint32_t OW = dst->ne[0];
  9515. const uint32_t parallel_elements = N * OC * OH * OW;
  9516. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  9517. IW, IH, OW, OH, OC,
  9518. parallel_elements,
  9519. op,
  9520. k0, k1, s0, s1, p0, p1,
  9521. });
  9522. }
  9523. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  9524. const ggml_tensor * src1, ggml_tensor * dst) {
  9525. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  9526. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9527. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  9528. GGML_TENSOR_BINARY_OP_LOCALS
  9529. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  9530. GGML_ASSERT(nb10 == sizeof(float));
  9531. GGML_ASSERT(nb0 == sizeof(float));
  9532. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  9533. vk_op_conv2d_push_constants p{};
  9534. p.Cout = static_cast<uint32_t>(!transpose ? ne03 : ne02);
  9535. p.Cin = static_cast<uint32_t>(!transpose ? ne02 : ne03);
  9536. p.N = static_cast<uint32_t>(ne13);
  9537. GGML_ASSERT(p.Cout == ne2);
  9538. GGML_ASSERT(p.Cin == ne12);
  9539. p.W = static_cast<uint32_t>(ne10);
  9540. p.H = static_cast<uint32_t>(ne11);
  9541. p.OW = static_cast<uint32_t>(ne0);
  9542. p.OH = static_cast<uint32_t>(ne1);
  9543. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9544. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9545. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  9546. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9547. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  9548. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  9549. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9550. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  9551. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  9552. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, dst->op, std::move(p));
  9553. }
  9554. static void ggml_vk_conv_2d_dw(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9555. vk_op_conv2d_dw_push_constants p{};
  9556. p.ne = ggml_nelements(dst);
  9557. p.channels = dst->ne[2];
  9558. p.batches = dst->ne[3];
  9559. p.dst_w = dst->ne[0];
  9560. p.dst_h = dst->ne[1];
  9561. p.src_w = src1->ne[0];
  9562. p.src_h = src1->ne[1];
  9563. p.knl_w = src0->ne[0];
  9564. p.knl_h = src0->ne[1];
  9565. p.stride_x = dst->op_params[0];
  9566. p.stride_y = dst->op_params[1];
  9567. p.pad_x = dst->op_params[2];
  9568. p.pad_y = dst->op_params[3];
  9569. p.dilation_x = dst->op_params[4];
  9570. p.dilation_y = dst->op_params[5];
  9571. GGML_ASSERT(src0->ne[3] == p.channels);
  9572. GGML_ASSERT(src1->ne[3] == p.batches);
  9573. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  9574. }
  9575. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9576. const float * op_params = (const float *)dst->op_params;
  9577. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f, 0.0f, 0.0f });
  9578. }
  9579. #ifdef GGML_VULKAN_RUN_TESTS
  9580. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  9581. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  9582. return;
  9583. }
  9584. i0 = std::max(i0, 5);
  9585. i1 = std::max(i1, 5);
  9586. i2 = std::max(i2, 0);
  9587. fprintf(stderr, " ");
  9588. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9589. fprintf(stderr, "%7d ", idx1);
  9590. }
  9591. fprintf(stderr, "\n");
  9592. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9593. fprintf(stderr, "%7d: ", idx0);
  9594. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9595. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  9596. float val;
  9597. if (type == GGML_TYPE_F32) {
  9598. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  9599. } else if (type == GGML_TYPE_F16) {
  9600. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  9601. } else {
  9602. GGML_ABORT("fatal error");
  9603. }
  9604. fprintf(stderr, "% 7.2f ", val);
  9605. } else {
  9606. fprintf(stderr, " ");
  9607. }
  9608. }
  9609. fprintf(stderr, "\n");
  9610. }
  9611. }
  9612. template <typename X_TYPE, typename Y_TYPE>
  9613. 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) {
  9614. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  9615. const size_t x_ne = m * k * batch;
  9616. const size_t y_ne = k * n * batch;
  9617. const size_t d_ne = m * n * batch;
  9618. vk_pipeline p;
  9619. std::string shname;
  9620. if (shader_size == 0) {
  9621. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9622. p = ctx->device->pipeline_matmul_f32->a_s;
  9623. shname = "F32_ALIGNED_S";
  9624. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9625. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  9626. shname = "F32_F16_ALIGNED_S";
  9627. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9628. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  9629. shname = "F16_F32_ALIGNED_S";
  9630. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9631. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  9632. shname = "F16_ALIGNED_S";
  9633. } else {
  9634. GGML_ABORT("fatal error");
  9635. }
  9636. } else if (shader_size == 1) {
  9637. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9638. p = ctx->device->pipeline_matmul_f32->a_m;
  9639. shname = "F32_ALIGNED_M";
  9640. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9641. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  9642. shname = "F32_F16_ALIGNED_M";
  9643. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9644. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  9645. shname = "F16_F32_ALIGNED_M";
  9646. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9647. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  9648. shname = "F16_ALIGNED_M";
  9649. } else {
  9650. GGML_ABORT("fatal error");
  9651. }
  9652. } else if (shader_size == 2) {
  9653. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9654. p = ctx->device->pipeline_matmul_f32->a_l;
  9655. shname = "F32_ALIGNED_L";
  9656. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9657. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  9658. shname = "F32_F16_ALIGNED_L";
  9659. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9660. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  9661. shname = "F16_F32_ALIGNED_L";
  9662. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9663. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  9664. shname = "F16_ALIGNED_L";
  9665. } else {
  9666. GGML_ABORT("fatal error");
  9667. }
  9668. } else {
  9669. GGML_ASSERT(0);
  9670. }
  9671. const size_t kpad = ggml_vk_align_size(k, p->align);
  9672. if (k != kpad) {
  9673. if (shader_size == 0) {
  9674. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9675. p = ctx->device->pipeline_matmul_f32->s;
  9676. shname = "F32_S";
  9677. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9678. p = ctx->device->pipeline_matmul_f32_f16->s;
  9679. shname = "F32_F16_S";
  9680. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9681. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  9682. shname = "F16_F32_S";
  9683. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9684. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  9685. shname = "F16_S";
  9686. }
  9687. } else if (shader_size == 1) {
  9688. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9689. p = ctx->device->pipeline_matmul_f32->m;
  9690. shname = "F32_M";
  9691. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9692. p = ctx->device->pipeline_matmul_f32_f16->m;
  9693. shname = "F32_F16_M";
  9694. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9695. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  9696. shname = "F16_F32_M";
  9697. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9698. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  9699. shname = "F16_M";
  9700. }
  9701. } else if (shader_size == 2) {
  9702. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9703. p = ctx->device->pipeline_matmul_f32->l;
  9704. shname = "F32_L";
  9705. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9706. p = ctx->device->pipeline_matmul_f32_f16->l;
  9707. shname = "F32_F16_L";
  9708. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9709. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  9710. shname = "F16_F32_L";
  9711. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9712. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  9713. shname = "F16_L";
  9714. }
  9715. }
  9716. }
  9717. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9718. if (split_k > 1) {
  9719. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9720. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9721. // Resize buffer
  9722. if (ctx->prealloc_split_k != nullptr) {
  9723. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9724. }
  9725. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9726. }
  9727. }
  9728. ggml_pipeline_allocate_descriptor_sets(ctx);
  9729. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9730. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9731. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9732. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9733. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9734. float* d = (float *) malloc(sizeof(float) * d_ne);
  9735. for (size_t i = 0; i < x_ne; i++) {
  9736. if (std::is_same<float, X_TYPE>()) {
  9737. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9738. // x[i] = 1.0f;
  9739. // x[i] = i + 1;
  9740. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9741. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9742. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9743. // x[i] = ggml_fp32_to_fp16(1.0f);
  9744. // x[i] = ggml_fp32_to_fp16(i + 1);
  9745. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9746. } else {
  9747. GGML_ABORT("fatal error");
  9748. }
  9749. }
  9750. for (size_t i = 0; i < y_ne; i++) {
  9751. if (std::is_same<float, Y_TYPE>()) {
  9752. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9753. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9754. // y[i] = i + 1;
  9755. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9756. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9757. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9758. // y[i] = ggml_fp32_to_fp16(i + 1);
  9759. } else {
  9760. GGML_ABORT("fatal error");
  9761. }
  9762. }
  9763. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9764. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9765. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9766. ggml_vk_ctx_begin(ctx->device, subctx);
  9767. for (size_t i = 0; i < num_it; i++) {
  9768. ggml_vk_matmul(
  9769. ctx, subctx, p, ggml_vk_subbuffer(ctx, d_X), ggml_vk_subbuffer(ctx, d_Y), ggml_vk_subbuffer(ctx, d_D), ggml_vk_subbuffer(ctx, ctx->prealloc_split_k),
  9770. m, n, k,
  9771. k, k, m, k*m, k*n, m*n,
  9772. split_k, batch, batch, batch, 1, 1, n
  9773. );
  9774. }
  9775. ggml_vk_ctx_end(subctx);
  9776. auto begin = std::chrono::high_resolution_clock::now();
  9777. ggml_vk_submit(subctx, ctx->fence);
  9778. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9779. ctx->device->device.resetFences({ ctx->fence });
  9780. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9781. auto end = std::chrono::high_resolution_clock::now();
  9782. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9783. // copy dst to host
  9784. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9785. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9786. ggml_init_params iparams = {
  9787. /*.mem_size =*/ 1024*1024*1024,
  9788. /*.mem_buffer =*/ NULL,
  9789. /*.no_alloc =*/ true,
  9790. };
  9791. ggml_context * ggml_ctx = ggml_init(iparams);
  9792. ggml_type src0_type;
  9793. ggml_type src1_type;
  9794. if (std::is_same<float, X_TYPE>()) {
  9795. src0_type = GGML_TYPE_F32;
  9796. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9797. src0_type = GGML_TYPE_F16;
  9798. } else {
  9799. GGML_ABORT("fatal error");
  9800. }
  9801. if (std::is_same<float, Y_TYPE>()) {
  9802. src1_type = GGML_TYPE_F32;
  9803. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9804. src1_type = GGML_TYPE_F16;
  9805. } else {
  9806. GGML_ABORT("fatal error");
  9807. }
  9808. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9809. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9810. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9811. src0_ggml->data = x;
  9812. src1_ggml->data = y;
  9813. tensor_ggml->data = d_chk;
  9814. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9815. ggml_build_forward_expand(cgraph, tensor_ggml);
  9816. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9817. ggml_free(ggml_ctx);
  9818. double avg_err = 0.0;
  9819. int first_err_n = -1;
  9820. int first_err_m = -1;
  9821. int first_err_b = -1;
  9822. for (size_t i = 0; i < m*n*batch; i++) {
  9823. double err = std::fabs(d[i] - d_chk[i]);
  9824. avg_err += err;
  9825. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9826. first_err_b = i / (m * n);
  9827. first_err_n = (i % (m * n)) / m;
  9828. first_err_m = (i % (m * n)) % m;
  9829. }
  9830. }
  9831. avg_err /= m * n;
  9832. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9833. 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;
  9834. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9835. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9836. std::cerr << "Actual result: " << std::endl << std::endl;
  9837. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9838. std::cerr << "Expected result: " << std::endl << std::endl;
  9839. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9840. if (split_k > 1) {
  9841. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9842. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9843. std::cerr << "d_buf0: " << std::endl << std::endl;
  9844. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9845. std::cerr << "d_buf1: " << std::endl << std::endl;
  9846. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9847. std::cerr << "d_buf2: " << std::endl << std::endl;
  9848. 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);
  9849. std::cerr << "d_buf3: " << std::endl << std::endl;
  9850. 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);
  9851. free(split_k_buf);
  9852. }
  9853. }
  9854. free(d_chk);
  9855. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9856. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9857. ggml_vk_destroy_buffer(d_X);
  9858. ggml_vk_destroy_buffer(d_Y);
  9859. ggml_vk_destroy_buffer(d_D);
  9860. free(x);
  9861. free(y);
  9862. free(d);
  9863. }
  9864. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9865. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9866. return;
  9867. }
  9868. i0 = std::max(i0, 5);
  9869. i1 = std::max(i1, 5);
  9870. i2 = std::max(i2, 0);
  9871. i3 = std::max(i3, 0);
  9872. fprintf(stderr, " ");
  9873. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9874. fprintf(stderr, "%7d ", idx1);
  9875. }
  9876. fprintf(stderr, "\n");
  9877. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9878. fprintf(stderr, "%7d: ", idx0);
  9879. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9880. 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]) {
  9881. float val;
  9882. if (tensor->type == GGML_TYPE_F32) {
  9883. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9884. } else if (tensor->type == GGML_TYPE_F16) {
  9885. 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]));
  9886. } else {
  9887. GGML_ABORT("fatal error");
  9888. }
  9889. fprintf(stderr, "% 7.2f ", val);
  9890. } else {
  9891. fprintf(stderr, " ");
  9892. }
  9893. }
  9894. fprintf(stderr, "\n");
  9895. }
  9896. }
  9897. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9898. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9899. }
  9900. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9901. if (quant == GGML_TYPE_F32) {
  9902. memcpy(to, from, sizeof(float) * ne);
  9903. return;
  9904. }
  9905. const auto * tt = ggml_get_type_traits(quant);
  9906. ggml_to_float_t dequant_fn = tt->to_float;
  9907. dequant_fn(from, to, ne);
  9908. }
  9909. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9910. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9911. const size_t x_sz = sizeof(float) * ne;
  9912. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9913. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9914. float * x = (float *) malloc(x_sz);
  9915. void * qx = malloc(qx_sz);
  9916. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9917. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9918. float * x_ref = (float *) malloc(x_sz);
  9919. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9920. for (size_t i = 0; i < ne; i++) {
  9921. x[i] = rand() / (float)RAND_MAX;
  9922. }
  9923. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9924. ggml_vk_quantize_data(x, qx, ne, quant);
  9925. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9926. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9927. ggml_pipeline_allocate_descriptor_sets(ctx);
  9928. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9929. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9930. ggml_vk_ctx_begin(ctx->device, subctx);
  9931. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9932. ggml_vk_dispatch_pipeline(ctx, subctx, p, { vk_subbuffer{ qx_buf, 0, qx_sz }, vk_subbuffer{ x_buf, 0, x_sz_f16 } }, pc, { (uint32_t)ne, 1, 1});
  9933. ggml_vk_ctx_end(subctx);
  9934. auto begin = std::chrono::high_resolution_clock::now();
  9935. ggml_vk_submit(subctx, ctx->fence);
  9936. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9937. ctx->device->device.resetFences({ ctx->fence });
  9938. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9939. auto end = std::chrono::high_resolution_clock::now();
  9940. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9941. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9942. int first_err = -1;
  9943. double avg_err = 0.0;
  9944. for (size_t i = 0; i < ne; i++) {
  9945. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9946. avg_err += error;
  9947. if (first_err < 0 && error > 0.05) {
  9948. first_err = i;
  9949. }
  9950. }
  9951. avg_err /= ne;
  9952. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9953. if (avg_err > 0.1) {
  9954. std::cerr << "first_error = " << first_err << std::endl;
  9955. std::cerr << "Actual result: " << std::endl << std::endl;
  9956. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9957. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9958. }
  9959. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9960. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9961. std::cerr << x_ref[i] << ", ";
  9962. }
  9963. std::cerr << std::endl;
  9964. }
  9965. ggml_vk_destroy_buffer(x_buf);
  9966. ggml_vk_destroy_buffer(qx_buf);
  9967. free(x);
  9968. free(qx);
  9969. free(x_ref);
  9970. free(x_chk);
  9971. }
  9972. // This does not work without ggml q8_1 quantization support
  9973. //
  9974. // typedef uint16_t ggml_half;
  9975. // typedef uint32_t ggml_half2;
  9976. //
  9977. // #define QK8_1 32
  9978. // typedef struct {
  9979. // union {
  9980. // struct {
  9981. // ggml_half d; // delta
  9982. // ggml_half s; // d * sum(qs[i])
  9983. // } GGML_COMMON_AGGR_S;
  9984. // ggml_half2 ds;
  9985. // } GGML_COMMON_AGGR_U;
  9986. // int8_t qs[QK8_1]; // quants
  9987. // } block_q8_1;
  9988. //
  9989. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9990. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9991. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9992. //
  9993. // const size_t x_sz = sizeof(float) * ne;
  9994. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9995. // float * x = (float *) malloc(x_sz);
  9996. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9997. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9998. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9999. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10000. //
  10001. // for (size_t i = 0; i < ne; i++) {
  10002. // x[i] = rand() / (float)RAND_MAX;
  10003. // }
  10004. //
  10005. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  10006. //
  10007. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  10008. //
  10009. // ggml_pipeline_allocate_descriptor_sets(ctx);
  10010. //
  10011. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  10012. //
  10013. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10014. // ggml_vk_ctx_begin(ctx->device, subctx);
  10015. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  10016. // ggml_vk_ctx_end(subctx);
  10017. //
  10018. // auto begin = std::chrono::high_resolution_clock::now();
  10019. //
  10020. // ggml_vk_submit(subctx, ctx->fence);
  10021. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  10022. // ctx->device->device.resetFences({ ctx->fence });
  10023. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  10024. //
  10025. // auto end = std::chrono::high_resolution_clock::now();
  10026. //
  10027. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  10028. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  10029. //
  10030. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  10031. //
  10032. // int first_err = -1;
  10033. //
  10034. // for (size_t i = 0; i < ne / 32; i++) {
  10035. // double error = std::fabs(ggml_fp16_to_fp32(qx_res[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) - ggml_fp16_to_fp32(qx[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d));
  10036. //
  10037. // if (first_err < 0 && error > 0.1) {
  10038. // first_err = i;
  10039. // }
  10040. //
  10041. // error = std::fabs(ggml_fp16_to_fp32(qx_res[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) - ggml_fp16_to_fp32(qx[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s));
  10042. //
  10043. // if (first_err < 0 && error > 0.1) {
  10044. // first_err = i;
  10045. // }
  10046. //
  10047. // for (size_t j = 0; j < 32; j++) {
  10048. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  10049. //
  10050. // if (first_err < 0 && error > 1) {
  10051. // first_err = i;
  10052. // }
  10053. // }
  10054. // }
  10055. //
  10056. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  10057. //
  10058. // if (first_err != -1) {
  10059. // std::cerr << "first_error = " << first_err << std::endl;
  10060. // std::cerr << "Actual result: " << std::endl << std::endl;
  10061. // std::cout << "d=" << ggml_fp16_to_fp32(qx[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) << " s=" << ggml_fp16_to_fp32(qx[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) << " ";
  10062. // for (size_t j = 0; j < 32; j++) {
  10063. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  10064. // }
  10065. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  10066. // std::cout << "d=" << ggml_fp16_to_fp32(qx_res[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) << " s=" << ggml_fp16_to_fp32(qx_res[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) << " ";
  10067. // for (size_t j = 0; j < 32; j++) {
  10068. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  10069. // }
  10070. // std::cerr << std::endl;
  10071. // }
  10072. //
  10073. // ggml_vk_destroy_buffer(x_buf);
  10074. // ggml_vk_destroy_buffer(qx_buf);
  10075. //
  10076. // free(x);
  10077. // free(qx);
  10078. // free(qx_res);
  10079. // }
  10080. 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, bool mmq = false) {
  10081. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  10082. const size_t x_ne = m * k * batch;
  10083. const size_t y_ne = k * n * batch;
  10084. const size_t d_ne = m * n * batch;
  10085. vk_matmul_pipeline2 * pipelines;
  10086. if (mmq) {
  10087. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  10088. } else {
  10089. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  10090. }
  10091. const bool fp16acc = ctx->device->fp16;
  10092. vk_pipeline p;
  10093. std::string shname;
  10094. if (shader_size == 0) {
  10095. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  10096. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  10097. } else if (shader_size == 1) {
  10098. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  10099. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  10100. } else if (shader_size == 2) {
  10101. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  10102. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  10103. } else {
  10104. GGML_ASSERT(0);
  10105. }
  10106. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  10107. if (mmq || k != kpad) {
  10108. if (shader_size == 0) {
  10109. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  10110. shname = std::string(ggml_type_name(quant)) + "_S";
  10111. } else if (shader_size == 1) {
  10112. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  10113. shname = std::string(ggml_type_name(quant)) + "_M";
  10114. } else if (shader_size == 2) {
  10115. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  10116. shname = std::string(ggml_type_name(quant)) + "_L";
  10117. } else {
  10118. GGML_ASSERT(0);
  10119. }
  10120. }
  10121. if (p == nullptr) {
  10122. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  10123. return;
  10124. }
  10125. const size_t x_sz = sizeof(float) * x_ne;
  10126. const size_t y_sz = sizeof(float) * y_ne;
  10127. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  10128. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  10129. const size_t d_sz = sizeof(float) * d_ne;
  10130. float * x = (float *) malloc(x_sz);
  10131. float * y = (float *) malloc(y_sz);
  10132. void * qx = malloc(qx_sz);
  10133. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10134. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10135. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10136. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10137. float * d = (float *) malloc(d_sz);
  10138. float * d_chk = (float *) malloc(d_sz);
  10139. for (size_t i = 0; i < x_ne; i++) {
  10140. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  10141. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  10142. // x[i] = i % k;
  10143. }
  10144. ggml_vk_quantize_data(x, qx, x_ne, quant);
  10145. for (size_t i = 0; i < y_ne; i++) {
  10146. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  10147. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  10148. // y[i] = i % k;
  10149. }
  10150. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  10151. if (split_k > 1) {
  10152. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  10153. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  10154. // Resize buffer
  10155. if (ctx->prealloc_split_k != nullptr) {
  10156. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10157. }
  10158. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10159. }
  10160. }
  10161. if (mmq) {
  10162. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  10163. }
  10164. ggml_pipeline_allocate_descriptor_sets(ctx);
  10165. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  10166. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  10167. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10168. ggml_vk_ctx_begin(ctx->device, subctx);
  10169. if (mmq) {
  10170. for (size_t i = 0; i < num_it; i++) {
  10171. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  10172. ggml_vk_matmul(
  10173. ctx, subctx, p, { qx_buf, 0, qx_sz }, { qy_buf, 0, qy_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k },
  10174. m, n, k,
  10175. k, k, m, k*m, k*n, m*n,
  10176. split_k, batch, batch, batch, 1, 1, n
  10177. );
  10178. }
  10179. } else {
  10180. for (size_t i = 0; i < num_it; i++) {
  10181. ggml_vk_matmul(
  10182. ctx, subctx, p, { qx_buf, 0, qx_sz }, { y_buf, 0, y_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k },
  10183. m, n, k,
  10184. k, k, m, k*m, k*n, m*n,
  10185. split_k, batch, batch, batch, 1, 1, n
  10186. );
  10187. }
  10188. }
  10189. ggml_vk_ctx_end(subctx);
  10190. auto begin = std::chrono::high_resolution_clock::now();
  10191. ggml_vk_submit(subctx, ctx->fence);
  10192. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  10193. ctx->device->device.resetFences({ ctx->fence });
  10194. ggml_vk_queue_command_pools_cleanup(ctx->device);
  10195. auto end = std::chrono::high_resolution_clock::now();
  10196. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  10197. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  10198. ggml_init_params iparams = {
  10199. /*.mem_size =*/ 1024*1024*1024,
  10200. /*.mem_buffer =*/ NULL,
  10201. /*.no_alloc =*/ true,
  10202. };
  10203. ggml_context * ggml_ctx = ggml_init(iparams);
  10204. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  10205. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  10206. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  10207. src0_ggml->data = qx;
  10208. src1_ggml->data = y;
  10209. tensor_ggml->data = d_chk;
  10210. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  10211. ggml_build_forward_expand(cgraph, tensor_ggml);
  10212. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  10213. ggml_free(ggml_ctx);
  10214. double avg_err = 0.0;
  10215. int first_err_n = -1;
  10216. int first_err_m = -1;
  10217. int first_err_b = -1;
  10218. for (size_t i = 0; i < m*n*batch; i++) {
  10219. double err = std::fabs(d[i] - d_chk[i]);
  10220. avg_err += err;
  10221. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  10222. first_err_b = i / (m * n);
  10223. first_err_n = (i % (m * n)) / m;
  10224. first_err_m = (i % (m * n)) % m;
  10225. }
  10226. }
  10227. avg_err /= m * n;
  10228. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  10229. std::cerr << "TEST dequant matmul " << shname;
  10230. if (mmq) {
  10231. std::cerr << " mmq";
  10232. }
  10233. std::cerr << " 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;
  10234. if (avg_err > 0.01 || std::isnan(avg_err)) {
  10235. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  10236. std::cerr << "Actual result: " << std::endl << std::endl;
  10237. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10238. std::cerr << std::endl;
  10239. std::cerr << "Expected result: " << std::endl << std::endl;
  10240. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10241. std::cerr << "src0: " << std::endl << std::endl;
  10242. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  10243. std::cerr << std::endl;
  10244. std::cerr << "src1: " << std::endl << std::endl;
  10245. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  10246. if (split_k > 1) {
  10247. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  10248. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  10249. std::cerr << "d_buf0: " << std::endl << std::endl;
  10250. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10251. std::cerr << "d_buf1: " << std::endl << std::endl;
  10252. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10253. std::cerr << "d_buf2: " << std::endl << std::endl;
  10254. 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);
  10255. std::cerr << "d_buf3: " << std::endl << std::endl;
  10256. 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);
  10257. free(split_k_buf);
  10258. }
  10259. }
  10260. ggml_vk_destroy_buffer(qx_buf);
  10261. ggml_vk_destroy_buffer(y_buf);
  10262. ggml_vk_destroy_buffer(qy_buf);
  10263. ggml_vk_destroy_buffer(d_buf);
  10264. free(x);
  10265. free(qx);
  10266. free(y);
  10267. free(d);
  10268. free(d_chk);
  10269. }
  10270. #endif
  10271. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  10272. #if defined(GGML_VULKAN_RUN_TESTS)
  10273. const std::vector<size_t> vals {
  10274. 512, 512, 128,
  10275. 128, 512, 512,
  10276. 4096, 512, 4096,
  10277. 11008, 512, 4096,
  10278. 4096, 512, 11008,
  10279. 32000, 512, 4096,
  10280. 8, 8, 8,
  10281. 100, 46, 576,
  10282. 623, 111, 128,
  10283. 100, 46, 558,
  10284. 512, 1, 256,
  10285. 128, 110, 622,
  10286. 511, 511, 127,
  10287. 511, 511, 7,
  10288. 511, 511, 17,
  10289. 49, 49, 128,
  10290. 128, 49, 49,
  10291. 4096, 49, 4096,
  10292. };
  10293. const size_t num_it = 100;
  10294. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  10295. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  10296. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  10297. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  10298. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  10299. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  10300. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  10301. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  10302. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  10303. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  10304. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  10305. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  10306. abort();
  10307. for (size_t i = 0; i < vals.size(); i += 3) {
  10308. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  10309. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  10310. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  10311. std::cerr << '\n';
  10312. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  10313. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  10314. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  10315. std::cerr << '\n';
  10316. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  10317. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  10318. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  10319. std::cerr << '\n' << std::endl;
  10320. if (vals[i + 2] % 32 == 0) {
  10321. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  10322. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  10323. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  10324. std::cerr << '\n';
  10325. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  10326. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  10327. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  10328. std::cerr << '\n';
  10329. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  10330. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  10331. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  10332. std::cerr << '\n' << std::endl;
  10333. }
  10334. if (vals[i + 2] % 256 == 0) {
  10335. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  10336. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  10337. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  10338. std::cerr << '\n';
  10339. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  10340. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  10341. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  10342. std::cerr << '\n';
  10343. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  10344. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  10345. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  10346. std::cerr << '\n' << std::endl;
  10347. }
  10348. }
  10349. GGML_ABORT("fatal error");
  10350. #endif
  10351. if (subctx) {
  10352. // Submit and wait for any pending work before reallocating the buffers
  10353. ggml_vk_ctx_end(subctx);
  10354. ggml_vk_submit(subctx, {});
  10355. ctx->submit_pending = true;
  10356. ggml_vk_synchronize(ctx);
  10357. ggml_vk_ctx_begin(ctx->device, subctx);
  10358. }
  10359. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  10360. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  10361. // Resize buffer
  10362. if (ctx->prealloc_x != nullptr) {
  10363. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10364. }
  10365. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  10366. }
  10367. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  10368. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  10369. // Resize buffer
  10370. if (ctx->prealloc_y != nullptr) {
  10371. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10372. }
  10373. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  10374. }
  10375. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  10376. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  10377. // Resize buffer
  10378. if (ctx->prealloc_split_k != nullptr) {
  10379. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10380. }
  10381. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  10382. }
  10383. if (ctx->prealloc_add_rms_partials == nullptr || (ctx->prealloc_size_add_rms_partials > 0 && ctx->prealloc_add_rms_partials->size < ctx->prealloc_size_add_rms_partials)) {
  10384. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  10385. // Resize buffer
  10386. if (ctx->prealloc_add_rms_partials != nullptr) {
  10387. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10388. }
  10389. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  10390. }
  10391. }
  10392. static void ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool almost_ready);
  10393. // Returns true if node has enqueued work into the queue, false otherwise
  10394. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  10395. static bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool last_node, bool almost_ready, bool submit){
  10396. ggml_tensor * node = cgraph->nodes[node_idx];
  10397. if (ggml_is_empty(node) || ggml_op_is_empty(node->op) || !node->buffer) {
  10398. return false;
  10399. }
  10400. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  10401. ctx->semaphore_idx = 0;
  10402. ggml_tensor * src0 = node->src[0];
  10403. ggml_tensor * src1 = node->src[1];
  10404. ggml_tensor * src2 = node->src[2];
  10405. ggml_tensor * src3 = node->src[3];
  10406. if (node->op == GGML_OP_ADD) {
  10407. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  10408. if (next_node_idx < cgraph->n_nodes &&
  10409. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  10410. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  10411. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  10412. ctx->device->add_rms_fusion) {
  10413. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  10414. ctx->do_add_rms_partials_offset_calculation = true;
  10415. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  10416. ctx->do_add_rms_partials = true;
  10417. }
  10418. }
  10419. }
  10420. vk_context compute_ctx;
  10421. if (ctx->compute_ctx.expired()) {
  10422. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10423. ctx->compute_ctx = compute_ctx;
  10424. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10425. } else {
  10426. compute_ctx = ctx->compute_ctx.lock();
  10427. }
  10428. {
  10429. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  10430. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  10431. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  10432. // outside of this logic. When a node uses one of the prealloc buffers for something like
  10433. // dequantization or split_k, additional synchronization is needed between those passes.
  10434. bool need_sync = false;
  10435. // Check whether "node" requires synchronization. The node requires synchronization if it
  10436. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  10437. // Destination nodes are checked against both the written/read lists. Source nodes are only
  10438. // checked against the written list. Two nodes overlap in memory if they come from the same
  10439. // buffer and the tensor or view ranges overlap.
  10440. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  10441. if (unsynced_nodes.size() == 0) {
  10442. return false;
  10443. }
  10444. auto n_base = vk_tensor_offset(node) + node->view_offs;
  10445. auto n_size = ggml_nbytes(node);
  10446. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  10447. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10448. for (auto &other : unsynced_nodes) {
  10449. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  10450. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  10451. if (a_buf == o_buf) {
  10452. auto o_base = vk_tensor_offset(other) + other->view_offs;
  10453. auto o_size = ggml_nbytes(other);
  10454. if ((o_base <= n_base && n_base < o_base + o_size) ||
  10455. (n_base <= o_base && o_base < n_base + n_size)) {
  10456. return true;
  10457. }
  10458. }
  10459. }
  10460. return false;
  10461. };
  10462. // For all fused ops, check if the destination node or any of the source
  10463. // nodes require synchronization.
  10464. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  10465. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10466. // If the node actually writes to memory, then check if it needs to sync
  10467. if (ctx->fused_ops_write_mask & (1 << i)) {
  10468. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  10469. need_sync = true;
  10470. break;
  10471. }
  10472. }
  10473. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10474. if (!cur_node->src[j]) {
  10475. continue;
  10476. }
  10477. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  10478. need_sync = true;
  10479. break;
  10480. }
  10481. }
  10482. }
  10483. if (need_sync) {
  10484. if (vk_enable_sync_logger) {
  10485. std::cerr << "sync" << std::endl;
  10486. }
  10487. ctx->unsynced_nodes_written.clear();
  10488. ctx->unsynced_nodes_read.clear();
  10489. ggml_vk_sync_buffers(ctx, compute_ctx);
  10490. if (vk_perf_logger_enabled && vk_perf_logger_concurrent) {
  10491. ctx->query_node_idx[ctx->query_idx] = node_idx;
  10492. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  10493. }
  10494. }
  10495. // Add all fused nodes to the unsynchronized lists.
  10496. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10497. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10498. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  10499. if (ctx->fused_ops_write_mask & (1 << i)) {
  10500. ctx->unsynced_nodes_written.push_back(cur_node);
  10501. }
  10502. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10503. if (!cur_node->src[j]) {
  10504. continue;
  10505. }
  10506. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  10507. }
  10508. }
  10509. }
  10510. if (vk_enable_sync_logger) {
  10511. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10512. auto *n = cgraph->nodes[node_idx + i];
  10513. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  10514. if (n->op == GGML_OP_GLU) {
  10515. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  10516. }
  10517. if (n->op == GGML_OP_ROPE) {
  10518. const int mode = ((const int32_t *) n->op_params)[2];
  10519. std::cerr << " rope mode: " << mode;
  10520. }
  10521. std::cerr << std::endl;
  10522. }
  10523. }
  10524. switch (node->op) {
  10525. case GGML_OP_REPEAT:
  10526. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  10527. break;
  10528. case GGML_OP_REPEAT_BACK:
  10529. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  10530. break;
  10531. case GGML_OP_ACC:
  10532. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  10533. break;
  10534. case GGML_OP_GET_ROWS:
  10535. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  10536. break;
  10537. case GGML_OP_ADD:
  10538. if (ctx->num_additional_fused_ops) {
  10539. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  10540. } else {
  10541. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  10542. }
  10543. break;
  10544. case GGML_OP_SUB:
  10545. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  10546. break;
  10547. case GGML_OP_MUL:
  10548. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  10549. break;
  10550. case GGML_OP_DIV:
  10551. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  10552. break;
  10553. case GGML_OP_ADD_ID:
  10554. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  10555. break;
  10556. case GGML_OP_CONCAT:
  10557. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  10558. break;
  10559. case GGML_OP_UPSCALE:
  10560. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  10561. break;
  10562. case GGML_OP_ADD1:
  10563. ggml_vk_add1(ctx, compute_ctx, src0, src1, node);
  10564. break;
  10565. case GGML_OP_ARANGE:
  10566. ggml_vk_arange(ctx, compute_ctx, node);
  10567. break;
  10568. case GGML_OP_FILL:
  10569. ggml_vk_fill(ctx, compute_ctx, node);
  10570. break;
  10571. case GGML_OP_SCALE:
  10572. ggml_vk_scale(ctx, compute_ctx, src0, node);
  10573. break;
  10574. case GGML_OP_SQR:
  10575. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  10576. break;
  10577. case GGML_OP_SQRT:
  10578. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  10579. break;
  10580. case GGML_OP_SIN:
  10581. ggml_vk_sin(ctx, compute_ctx, src0, node);
  10582. break;
  10583. case GGML_OP_COS:
  10584. ggml_vk_cos(ctx, compute_ctx, src0, node);
  10585. break;
  10586. case GGML_OP_LOG:
  10587. ggml_vk_log(ctx, compute_ctx, src0, node);
  10588. break;
  10589. case GGML_OP_TRI:
  10590. ggml_vk_tri(ctx, compute_ctx, src0, node);
  10591. break;
  10592. case GGML_OP_DIAG:
  10593. ggml_vk_diag(ctx, compute_ctx, src0, node);
  10594. break;
  10595. case GGML_OP_CLAMP:
  10596. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  10597. break;
  10598. case GGML_OP_PAD:
  10599. ggml_vk_pad(ctx, compute_ctx, src0, node);
  10600. break;
  10601. case GGML_OP_ROLL:
  10602. ggml_vk_roll(ctx, compute_ctx, src0, node);
  10603. break;
  10604. case GGML_OP_CPY:
  10605. case GGML_OP_CONT:
  10606. case GGML_OP_DUP:
  10607. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  10608. break;
  10609. case GGML_OP_SET_ROWS:
  10610. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  10611. break;
  10612. case GGML_OP_SILU_BACK:
  10613. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  10614. break;
  10615. case GGML_OP_NORM:
  10616. ggml_vk_norm(ctx, compute_ctx, src0, node);
  10617. break;
  10618. case GGML_OP_GROUP_NORM:
  10619. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  10620. break;
  10621. case GGML_OP_RMS_NORM:
  10622. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  10623. break;
  10624. case GGML_OP_RMS_NORM_BACK:
  10625. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  10626. break;
  10627. case GGML_OP_L2_NORM:
  10628. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  10629. break;
  10630. case GGML_OP_UNARY:
  10631. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10632. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10633. break;
  10634. }
  10635. switch (ggml_get_unary_op(node)) {
  10636. case GGML_UNARY_OP_EXP:
  10637. case GGML_UNARY_OP_SILU:
  10638. case GGML_UNARY_OP_GELU:
  10639. case GGML_UNARY_OP_GELU_ERF:
  10640. case GGML_UNARY_OP_GELU_QUICK:
  10641. case GGML_UNARY_OP_RELU:
  10642. case GGML_UNARY_OP_NEG:
  10643. case GGML_UNARY_OP_TANH:
  10644. case GGML_UNARY_OP_SIGMOID:
  10645. case GGML_UNARY_OP_HARDSIGMOID:
  10646. case GGML_UNARY_OP_HARDSWISH:
  10647. case GGML_UNARY_OP_ABS:
  10648. case GGML_UNARY_OP_SOFTPLUS:
  10649. case GGML_UNARY_OP_STEP:
  10650. case GGML_UNARY_OP_ROUND:
  10651. case GGML_UNARY_OP_CEIL:
  10652. case GGML_UNARY_OP_FLOOR:
  10653. case GGML_UNARY_OP_TRUNC:
  10654. ggml_vk_unary(ctx, compute_ctx, src0, node);
  10655. break;
  10656. case GGML_UNARY_OP_XIELU:
  10657. ggml_vk_xielu(ctx, compute_ctx, src0, node);
  10658. break;
  10659. default:
  10660. return false;
  10661. }
  10662. break;
  10663. case GGML_OP_GLU:
  10664. switch (ggml_get_glu_op(node)) {
  10665. case GGML_GLU_OP_GEGLU:
  10666. case GGML_GLU_OP_REGLU:
  10667. case GGML_GLU_OP_SWIGLU:
  10668. case GGML_GLU_OP_SWIGLU_OAI:
  10669. case GGML_GLU_OP_GEGLU_ERF:
  10670. case GGML_GLU_OP_GEGLU_QUICK:
  10671. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  10672. break;
  10673. default:
  10674. return false;
  10675. }
  10676. break;
  10677. case GGML_OP_DIAG_MASK_INF:
  10678. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  10679. break;
  10680. case GGML_OP_SOFT_MAX:
  10681. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10682. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10683. } else {
  10684. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  10685. }
  10686. break;
  10687. case GGML_OP_SOFT_MAX_BACK:
  10688. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  10689. break;
  10690. case GGML_OP_ROPE:
  10691. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  10692. break;
  10693. case GGML_OP_ROPE_BACK:
  10694. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  10695. break;
  10696. case GGML_OP_ARGSORT:
  10697. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10698. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10699. } else {
  10700. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10701. }
  10702. break;
  10703. case GGML_OP_TOP_K:
  10704. ggml_vk_topk(ctx, compute_ctx, src0, node);
  10705. break;
  10706. case GGML_OP_SUM:
  10707. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10708. break;
  10709. case GGML_OP_SUM_ROWS:
  10710. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10711. break;
  10712. case GGML_OP_CUMSUM:
  10713. ggml_vk_cumsum(ctx, compute_ctx, src0, node);
  10714. break;
  10715. case GGML_OP_MEAN:
  10716. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10717. break;
  10718. case GGML_OP_ARGMAX:
  10719. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10720. break;
  10721. case GGML_OP_COUNT_EQUAL:
  10722. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10723. break;
  10724. case GGML_OP_SOLVE_TRI:
  10725. ggml_vk_solve_tri(ctx, compute_ctx, src0, src1, node);
  10726. break;
  10727. case GGML_OP_IM2COL:
  10728. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10729. break;
  10730. case GGML_OP_IM2COL_3D:
  10731. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10732. break;
  10733. case GGML_OP_TIMESTEP_EMBEDDING:
  10734. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10735. break;
  10736. case GGML_OP_CONV_TRANSPOSE_1D:
  10737. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10738. break;
  10739. case GGML_OP_POOL_2D:
  10740. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10741. break;
  10742. case GGML_OP_CONV_2D:
  10743. case GGML_OP_CONV_TRANSPOSE_2D:
  10744. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10745. break;
  10746. case GGML_OP_CONV_2D_DW:
  10747. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10748. break;
  10749. case GGML_OP_LEAKY_RELU:
  10750. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10751. break;
  10752. case GGML_OP_MUL_MAT:
  10753. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10754. break;
  10755. case GGML_OP_MUL_MAT_ID:
  10756. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10757. break;
  10758. case GGML_OP_FLASH_ATTN_EXT:
  10759. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10760. break;
  10761. case GGML_OP_RWKV_WKV6:
  10762. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10763. break;
  10764. case GGML_OP_RWKV_WKV7:
  10765. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10766. break;
  10767. case GGML_OP_SSM_SCAN:
  10768. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10769. break;
  10770. case GGML_OP_SSM_CONV:
  10771. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10772. break;
  10773. case GGML_OP_OPT_STEP_ADAMW:
  10774. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10775. break;
  10776. case GGML_OP_OPT_STEP_SGD:
  10777. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10778. break;
  10779. default:
  10780. return false;
  10781. }
  10782. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10783. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10784. // Force context reset on each node so that each tensor ends up in its own context
  10785. // and can be run and compared to its CPU equivalent separately
  10786. last_node = true;
  10787. #endif
  10788. if (submit || last_node) {
  10789. ggml_vk_ctx_end(compute_ctx);
  10790. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10791. if (last_node) {
  10792. compute_ctx->exit_tensor_idx = node_idx_begin;
  10793. }
  10794. else {
  10795. compute_ctx->exit_tensor_idx = -1;
  10796. }
  10797. ctx->compute_ctx.reset();
  10798. ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready);
  10799. }
  10800. return true;
  10801. }
  10802. static void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready = false) {
  10803. GGML_UNUSED(cgraph);
  10804. GGML_UNUSED(tensor);
  10805. 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 << ")");
  10806. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10807. // Only run if ctx hasn't been submitted yet
  10808. if (!subctx->seqs.empty()) {
  10809. #ifdef GGML_VULKAN_CHECK_RESULTS
  10810. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10811. #endif
  10812. // Do staging buffer copies
  10813. for (auto& cpy : subctx->in_memcpys) {
  10814. memcpy(cpy.dst, cpy.src, cpy.n);
  10815. }
  10816. for (auto& mset : subctx->memsets) {
  10817. memset(mset.dst, mset.val, mset.n);
  10818. }
  10819. if (almost_ready && !ctx->almost_ready_fence_pending) {
  10820. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10821. ctx->almost_ready_fence_pending = true;
  10822. } else {
  10823. ggml_vk_submit(subctx, {});
  10824. }
  10825. ctx->submit_pending = true;
  10826. #ifdef GGML_VULKAN_CHECK_RESULTS
  10827. ggml_vk_synchronize(ctx);
  10828. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10829. #endif
  10830. }
  10831. if (tensor_idx == subctx->exit_tensor_idx) {
  10832. // Do staging buffer copies
  10833. for (auto& cpy : subctx->out_memcpys) {
  10834. memcpy(cpy.dst, cpy.src, cpy.n);
  10835. }
  10836. subctx->in_memcpys.clear();
  10837. subctx->out_memcpys.clear();
  10838. subctx->memsets.clear();
  10839. }
  10840. }
  10841. // Clean up after graph processing is done
  10842. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10843. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10844. ctx->prealloc_y_last_pipeline_used = {};
  10845. ctx->unsynced_nodes_written.clear();
  10846. ctx->unsynced_nodes_read.clear();
  10847. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10848. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10849. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10850. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10851. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10852. }
  10853. ctx->gc.semaphores.clear();
  10854. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10855. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10856. }
  10857. ctx->gc.tl_semaphores.clear();
  10858. ctx->semaphore_idx = 0;
  10859. ctx->event_idx = 0;
  10860. for (auto& event : ctx->gc.events) {
  10861. ctx->device->device.resetEvent(event);
  10862. }
  10863. ctx->tensor_ctxs.clear();
  10864. ctx->gc.contexts.clear();
  10865. ctx->pipeline_descriptor_set_requirements = 0;
  10866. ctx->descriptor_set_idx = 0;
  10867. }
  10868. // Clean up on backend free
  10869. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10870. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10871. // discard any unsubmitted command buffers
  10872. ctx->transfer_ctx.reset();
  10873. // wait for any pending command buffers to finish
  10874. ggml_vk_synchronize(ctx);
  10875. ggml_vk_graph_cleanup(ctx);
  10876. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10877. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10878. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10879. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10880. ggml_vk_destroy_buffer(ctx->sync_staging);
  10881. ctx->prealloc_y_last_pipeline_used = nullptr;
  10882. ctx->prealloc_size_x = 0;
  10883. ctx->prealloc_size_y = 0;
  10884. ctx->prealloc_size_split_k = 0;
  10885. for (auto& event : ctx->gc.events) {
  10886. ctx->device->device.destroyEvent(event);
  10887. }
  10888. ctx->gc.events.clear();
  10889. ctx->device->device.destroyFence(ctx->fence);
  10890. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10891. for (auto& pool : ctx->descriptor_pools) {
  10892. ctx->device->device.destroyDescriptorPool(pool);
  10893. }
  10894. ctx->descriptor_pools.clear();
  10895. ctx->descriptor_sets.clear();
  10896. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10897. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10898. if (vk_perf_logger_enabled) {
  10899. ctx->perf_logger->print_timings(true);
  10900. }
  10901. }
  10902. static int ggml_vk_get_device_count() {
  10903. ggml_vk_instance_init();
  10904. return vk_instance.device_indices.size();
  10905. }
  10906. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10907. ggml_vk_instance_init();
  10908. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10909. vk::PhysicalDeviceProperties props;
  10910. devices[device].getProperties(&props);
  10911. snprintf(description, description_size, "%s", props.deviceName.data());
  10912. }
  10913. // backend interface
  10914. #define UNUSED GGML_UNUSED
  10915. // device backend
  10916. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10917. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10918. }
  10919. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10920. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10921. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10922. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10923. delete ctx;
  10924. }
  10925. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10926. return vk_ptr_base;
  10927. UNUSED(buffer);
  10928. }
  10929. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10930. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10931. if (tensor->view_src != nullptr) {
  10932. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10933. }
  10934. return GGML_STATUS_SUCCESS;
  10935. }
  10936. static void ggml_backend_vk_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
  10937. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10938. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10939. vk_buffer buf = buf_ctx->dev_buffer;
  10940. uint32_t val32 = (uint32_t)value * 0x01010101;
  10941. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10942. }
  10943. 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) {
  10944. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10945. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10946. vk_buffer buf = buf_ctx->dev_buffer;
  10947. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10948. }
  10949. 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) {
  10950. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10951. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10952. vk_buffer buf = buf_ctx->dev_buffer;
  10953. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10954. }
  10955. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10956. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10957. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10958. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10959. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10960. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10961. 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));
  10962. return true;
  10963. }
  10964. return false;
  10965. UNUSED(buffer);
  10966. }
  10967. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10968. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10969. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10970. }
  10971. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10972. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10973. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10974. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10975. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10976. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10977. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10978. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10979. /* .clear = */ ggml_backend_vk_buffer_clear,
  10980. /* .reset = */ NULL,
  10981. };
  10982. // vk buffer type
  10983. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10984. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10985. return ctx->name.c_str();
  10986. }
  10987. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10988. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10989. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10990. vk_buffer dev_buffer = nullptr;
  10991. try {
  10992. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10993. } catch (const vk::SystemError& e) {
  10994. return nullptr;
  10995. }
  10996. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10997. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10998. }
  10999. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  11000. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  11001. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  11002. }
  11003. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  11004. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  11005. return ctx->device->suballocation_block_size;
  11006. }
  11007. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  11008. return ggml_nbytes(tensor);
  11009. UNUSED(buft);
  11010. }
  11011. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  11012. ggml_vk_instance_init();
  11013. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  11014. vk_device dev = ggml_vk_get_device(dev_num);
  11015. return &dev->buffer_type;
  11016. }
  11017. // host buffer type
  11018. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  11019. return GGML_VK_NAME "_Host";
  11020. UNUSED(buft);
  11021. }
  11022. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  11023. return GGML_VK_NAME "_Host";
  11024. UNUSED(buffer);
  11025. }
  11026. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  11027. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  11028. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  11029. }
  11030. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  11031. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  11032. size += 32; // Behave like the CPU buffer type
  11033. void * ptr = nullptr;
  11034. try {
  11035. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  11036. } catch (vk::SystemError& e) {
  11037. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  11038. // fallback to cpu buffer
  11039. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  11040. }
  11041. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  11042. buffer->buft = buft;
  11043. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  11044. return buffer;
  11045. UNUSED(buft);
  11046. }
  11047. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  11048. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  11049. UNUSED(buft);
  11050. }
  11051. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  11052. return vk_instance.devices[0]->suballocation_block_size;
  11053. UNUSED(buft);
  11054. }
  11055. // Should be changed to return device-specific host buffer type
  11056. // but that probably requires changes in llama.cpp
  11057. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  11058. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  11059. /* .iface = */ {
  11060. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  11061. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  11062. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  11063. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  11064. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  11065. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  11066. },
  11067. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  11068. /* .context = */ nullptr,
  11069. };
  11070. // Make sure device 0 is initialized
  11071. ggml_vk_instance_init();
  11072. ggml_vk_get_device(0);
  11073. return &ggml_backend_vk_buffer_type_host;
  11074. }
  11075. // backend
  11076. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  11077. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11078. return ctx->name.c_str();
  11079. }
  11080. static void ggml_backend_vk_free(ggml_backend_t backend) {
  11081. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11082. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  11083. ggml_vk_cleanup(ctx);
  11084. delete ctx;
  11085. delete backend;
  11086. }
  11087. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  11088. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11089. return &ctx->device->buffer_type;
  11090. }
  11091. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  11092. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  11093. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11094. 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");
  11095. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11096. vk_context transfer_ctx;
  11097. if (ctx->transfer_ctx.expired()) {
  11098. // Initialize new transfer context
  11099. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11100. ctx->transfer_ctx = transfer_ctx;
  11101. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11102. } else {
  11103. transfer_ctx = ctx->transfer_ctx.lock();
  11104. }
  11105. vk_buffer buf = buf_ctx->dev_buffer;
  11106. auto dst_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  11107. bool ret = ggml_vk_buffer_write_async(transfer_ctx, buf, dst_offset, data, size);
  11108. if (!ret) {
  11109. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  11110. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  11111. vk::BufferCopy buffer_cpy;
  11112. buffer_cpy.srcOffset = 0;
  11113. buffer_cpy.dstOffset = dst_offset;
  11114. buffer_cpy.size = size;
  11115. transfer_ctx->s->buffer.copyBuffer(ctx->sync_staging->buffer, buf->buffer, { buffer_cpy });
  11116. deferred_memcpy(ctx->sync_staging->ptr, data, size, &transfer_ctx->in_memcpys);
  11117. ggml_vk_synchronize(ctx);
  11118. }
  11119. }
  11120. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  11121. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  11122. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11123. 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");
  11124. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11125. vk_context transfer_ctx;
  11126. if (ctx->transfer_ctx.expired()) {
  11127. // Initialize new transfer context
  11128. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11129. ctx->transfer_ctx = transfer_ctx;
  11130. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11131. } else {
  11132. transfer_ctx = ctx->transfer_ctx.lock();
  11133. }
  11134. vk_buffer buf = buf_ctx->dev_buffer;
  11135. auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  11136. bool ret = ggml_vk_buffer_read_async(transfer_ctx, buf, src_offset, data, size);
  11137. // If that failed, copy synchronously through a staging buffer
  11138. if (!ret) {
  11139. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  11140. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  11141. vk::BufferCopy buffer_cpy;
  11142. buffer_cpy.srcOffset = src_offset;
  11143. buffer_cpy.dstOffset = 0;
  11144. buffer_cpy.size = size;
  11145. transfer_ctx->s->buffer.copyBuffer(buf->buffer, ctx->sync_staging->buffer, { buffer_cpy });
  11146. deferred_memcpy(data, ctx->sync_staging->ptr, size, &transfer_ctx->out_memcpys);
  11147. ggml_vk_synchronize(ctx);
  11148. }
  11149. }
  11150. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  11151. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  11152. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11153. 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)) {
  11154. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  11155. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  11156. vk_context transfer_ctx;
  11157. if (ctx->transfer_ctx.expired()) {
  11158. // Initialize new transfer context
  11159. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11160. ctx->transfer_ctx = transfer_ctx;
  11161. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11162. } else {
  11163. transfer_ctx = ctx->transfer_ctx.lock();
  11164. }
  11165. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  11166. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  11167. 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));
  11168. return true;
  11169. }
  11170. return false;
  11171. }
  11172. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx) {
  11173. VK_LOG_DEBUG("ggml_vk_synchronize()");
  11174. bool do_transfer = !ctx->transfer_ctx.expired();
  11175. vk_context transfer_ctx;
  11176. if (do_transfer) {
  11177. transfer_ctx = ctx->transfer_ctx.lock();
  11178. ggml_vk_ctx_end(transfer_ctx);
  11179. for (auto& cpy : transfer_ctx->in_memcpys) {
  11180. memcpy(cpy.dst, cpy.src, cpy.n);
  11181. }
  11182. ggml_vk_submit(transfer_ctx, {});
  11183. ctx->submit_pending = true;
  11184. }
  11185. if (ctx->submit_pending) {
  11186. {
  11187. std::lock_guard<std::mutex> guard(queue_mutex);
  11188. ctx->device->compute_queue.queue.submit({}, ctx->fence);
  11189. }
  11190. ggml_vk_wait_for_fence(ctx);
  11191. ctx->submit_pending = false;
  11192. }
  11193. if (do_transfer) {
  11194. for (auto& cpy : transfer_ctx->out_memcpys) {
  11195. memcpy(cpy.dst, cpy.src, cpy.n);
  11196. }
  11197. ctx->transfer_ctx.reset();
  11198. }
  11199. }
  11200. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  11201. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  11202. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11203. ggml_vk_synchronize(ctx);
  11204. ggml_vk_graph_cleanup(ctx);
  11205. }
  11206. static bool ggml_vk_is_empty(ggml_tensor * node) {
  11207. 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;
  11208. }
  11209. static bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  11210. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  11211. return false;
  11212. }
  11213. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  11214. // additional constraints specific to this fusion
  11215. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  11216. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11217. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  11218. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  11219. // rms_norm only supports f32
  11220. if (mul->src[0]->type != GGML_TYPE_F32 ||
  11221. mul->src[1]->type != GGML_TYPE_F32 ||
  11222. mul->type != GGML_TYPE_F32) {
  11223. return false;
  11224. }
  11225. // if rms_norm is the B operand, then we don't handle broadcast
  11226. if (rms_norm == mul->src[1] &&
  11227. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  11228. return false;
  11229. }
  11230. // rms_norm shader assumes contiguous rows
  11231. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  11232. return false;
  11233. }
  11234. }
  11235. auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) {
  11236. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  11237. // mat-vec only
  11238. if (ggml_nrows(mul) != 1) {
  11239. return false;
  11240. }
  11241. // shaders assume the types match
  11242. if (mul->type != bias->type) {
  11243. return false;
  11244. }
  11245. // shaders reuse the D shape for bias
  11246. if (!ggml_are_same_shape(mul, bias) ||
  11247. !ggml_are_same_stride(mul, bias)) {
  11248. return false;
  11249. }
  11250. // unaligned bias isn't handled
  11251. if (get_misalign_bytes(ctx, bias) != 0) {
  11252. return false;
  11253. }
  11254. return true;
  11255. };
  11256. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  11257. // additional constraints specific to this fusion
  11258. const ggml_tensor *mul = cgraph->nodes[node_idx];
  11259. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  11260. if (!mm_add_ok(mul, add)) {
  11261. return false;
  11262. }
  11263. if (ops.size() == 3) {
  11264. if (ops.begin()[2] != GGML_OP_ADD) {
  11265. return false;
  11266. }
  11267. if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) {
  11268. return false;
  11269. }
  11270. }
  11271. }
  11272. auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) {
  11273. const ggml_tensor *scale = mul->src[1];
  11274. if (mmid != mul->src[0]) {
  11275. return false;
  11276. }
  11277. // mat-vec only
  11278. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  11279. return false;
  11280. }
  11281. // shaders assume the types match
  11282. if (mmid->type != scale->type) {
  11283. return false;
  11284. }
  11285. // shaders assume the bias is contiguous
  11286. if (!ggml_is_contiguous(scale)) {
  11287. return false;
  11288. }
  11289. // unaligned bias isn't handled
  11290. if (get_misalign_bytes(ctx, scale) != 0) {
  11291. return false;
  11292. }
  11293. // shader only indexes by expert index
  11294. if (scale->ne[0] != 1 ||
  11295. scale->ne[1] != mul->ne[1] ||
  11296. scale->ne[2] != 1 ||
  11297. scale->ne[3] != 1) {
  11298. return false;
  11299. }
  11300. return true;
  11301. };
  11302. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  11303. // additional constraints specific to this fusion
  11304. const ggml_tensor *mul = cgraph->nodes[node_idx];
  11305. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  11306. const ggml_tensor *bias = add->src[1];
  11307. if (mul != add->src[0]) {
  11308. return false;
  11309. }
  11310. // mat-vec only
  11311. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  11312. return false;
  11313. }
  11314. // shaders assume the types match
  11315. if (mul->type != bias->type) {
  11316. return false;
  11317. }
  11318. // shaders assume the bias is contiguous
  11319. if (!ggml_is_contiguous(bias)) {
  11320. return false;
  11321. }
  11322. // the ID tensor must be the same for mul_mat_id and add_id
  11323. if (mul->src[2] != add->src[2]) {
  11324. return false;
  11325. }
  11326. // unaligned bias isn't handled
  11327. if (get_misalign_bytes(ctx, bias) != 0) {
  11328. return false;
  11329. }
  11330. if (ops.size() == 3) {
  11331. if (ops.begin()[2] != GGML_OP_MUL) {
  11332. return false;
  11333. }
  11334. const ggml_tensor *mul = cgraph->nodes[node_idx + 2];
  11335. return mmid_mul_ok(add, mul);
  11336. }
  11337. }
  11338. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  11339. // additional constraints specific to this fusion
  11340. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  11341. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11342. if (!mmid_mul_ok(mmid, mul)) {
  11343. return false;
  11344. }
  11345. }
  11346. return true;
  11347. }
  11348. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11349. int node_idx, topk_moe_mode mode) {
  11350. const ggml_tensor * softmax;
  11351. const ggml_tensor * weights;
  11352. const ggml_tensor * get_rows;
  11353. const ggml_tensor * argsort;
  11354. switch (mode) {
  11355. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  11356. softmax = cgraph->nodes[node_idx + 0];
  11357. weights = cgraph->nodes[node_idx + 9];
  11358. get_rows = cgraph->nodes[node_idx + 4];
  11359. argsort = cgraph->nodes[node_idx + 2];
  11360. break;
  11361. case TOPK_MOE_SIGMOID_NORM_BIAS:
  11362. softmax = cgraph->nodes[node_idx + 0]; // really sigmoid
  11363. weights = cgraph->nodes[node_idx + 10];
  11364. get_rows = cgraph->nodes[node_idx + 5];
  11365. argsort = cgraph->nodes[node_idx + 3];
  11366. if (ggml_get_unary_op(softmax) != GGML_UNARY_OP_SIGMOID) {
  11367. return false;
  11368. }
  11369. // bias is expected to be 1D
  11370. if (ggml_nrows(cgraph->nodes[node_idx + 2]->src[1]) != 1 ||
  11371. !ggml_is_contiguous(cgraph->nodes[node_idx + 2]->src[1])) {
  11372. return false;
  11373. }
  11374. // sigmoid fusion seems to generate infinities on moltenvk
  11375. if (ctx->device->driver_id == vk::DriverId::eMoltenvk) {
  11376. return false;
  11377. }
  11378. break;
  11379. case TOPK_MOE_EARLY_SOFTMAX:
  11380. softmax = cgraph->nodes[node_idx + 0];
  11381. weights = cgraph->nodes[node_idx + 4];
  11382. get_rows = cgraph->nodes[node_idx + 4];
  11383. argsort = cgraph->nodes[node_idx + 2];
  11384. break;
  11385. case TOPK_MOE_LATE_SOFTMAX:
  11386. softmax = cgraph->nodes[node_idx + 4];
  11387. weights = cgraph->nodes[node_idx + 5];
  11388. get_rows = cgraph->nodes[node_idx + 2];
  11389. argsort = cgraph->nodes[node_idx + 0];
  11390. break;
  11391. default:
  11392. return false;
  11393. }
  11394. ggml_tensor * probs = get_rows->src[0];
  11395. if (probs->op != GGML_OP_RESHAPE) {
  11396. return false;
  11397. }
  11398. probs = probs->src[0];
  11399. ggml_tensor * selection_probs = argsort->src[0];
  11400. if (probs != selection_probs && mode != TOPK_MOE_SIGMOID_NORM_BIAS) {
  11401. return false;
  11402. }
  11403. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  11404. return false;
  11405. }
  11406. if (softmax->op == GGML_OP_SOFT_MAX) {
  11407. const float * op_params = (const float *)softmax->op_params;
  11408. float scale = op_params[0];
  11409. float max_bias = op_params[1];
  11410. if (scale != 1.0f || max_bias != 0.0f) {
  11411. return false;
  11412. }
  11413. // don't fuse when masks or sinks are present
  11414. if (softmax->src[1] || softmax->src[2]) {
  11415. return false;
  11416. }
  11417. }
  11418. const int n_expert = softmax->ne[0];
  11419. if (n_expert > (1 << (num_topk_moe_pipelines-1))) {
  11420. return false;
  11421. }
  11422. if (!ctx->device->subgroup_arithmetic ||
  11423. !ctx->device->subgroup_shuffle ||
  11424. !ctx->device->subgroup_require_full_support ||
  11425. ctx->device->disable_fusion) {
  11426. return false;
  11427. }
  11428. return true;
  11429. }
  11430. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11431. int node_idx) {
  11432. GGML_UNUSED(ctx);
  11433. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  11434. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  11435. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  11436. // ne3 not tested
  11437. if (rope->src[0]->ne[3] != 1) {
  11438. return false;
  11439. }
  11440. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  11441. return false;
  11442. }
  11443. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  11444. return false;
  11445. }
  11446. // The view should flatten two dims of rope into one dim
  11447. if (!ggml_is_contiguous(view) ||
  11448. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  11449. return false;
  11450. }
  11451. // Only norm/neox/mrope shaders have the fusion code
  11452. const int mode = ((const int32_t *) rope->op_params)[2];
  11453. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_MROPE) {
  11454. return false;
  11455. }
  11456. return true;
  11457. }
  11458. // Check whether the tensors overlap in memory but are not equal.
  11459. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  11460. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  11461. // to overlap if they are exactly equal.
  11462. // XXX TODO this check is probably missing from several fusion optimizations.
  11463. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  11464. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  11465. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  11466. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  11467. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  11468. if (a_buf == b_buf) {
  11469. auto a_base = vk_tensor_offset(a) + a->view_offs;
  11470. auto a_size = ggml_nbytes(a);
  11471. auto b_base = vk_tensor_offset(b) + b->view_offs;
  11472. auto b_size = ggml_nbytes(b);
  11473. if (a_base == b_base && a_size == b_size) {
  11474. return false;
  11475. }
  11476. if ((b_base <= a_base && a_base < b_base + b_size) ||
  11477. (a_base <= b_base && b_base < a_base + a_size)) {
  11478. return true;
  11479. }
  11480. }
  11481. return false;
  11482. }
  11483. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11484. int node_idx) {
  11485. GGML_UNUSED(ctx);
  11486. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  11487. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11488. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  11489. const int mode = ((const int32_t *) rope->op_params)[2];
  11490. // noncontig tensors aren't tested, and don't seem common in practice
  11491. if (!ggml_is_contiguous(rms) ||
  11492. !ggml_is_contiguous(mul) ||
  11493. !ggml_is_contiguous(rope)) {
  11494. return false;
  11495. }
  11496. // only norm/neox are handled in the shader
  11497. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  11498. return false;
  11499. }
  11500. // shared memory size for passing data from mul->rope
  11501. if (mul->ne[0] > 1024) {
  11502. return false;
  11503. }
  11504. // must not overwrite srcs in a way that's not elementwise
  11505. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  11506. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  11507. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  11508. return false;
  11509. }
  11510. // conditions for pipeline creation
  11511. if (!(ctx->device->float_controls_rte_fp16 &&
  11512. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= ctx->device->properties.limits.maxPushConstantsSize)) {
  11513. return false;
  11514. }
  11515. return true;
  11516. }
  11517. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  11518. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  11519. if (first_node->op != GGML_OP_ADD) {
  11520. return 0;
  11521. }
  11522. if (!ctx->device->multi_add) {
  11523. return 0;
  11524. }
  11525. int32_t num_adds = 1;
  11526. while (node_idx + num_adds < cgraph->n_nodes &&
  11527. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  11528. num_adds < MAX_FUSED_ADDS) {
  11529. num_adds++;
  11530. }
  11531. // The shader currently requires same shapes (but different strides are allowed),
  11532. // everything f32, and no misalignment
  11533. for (int32_t i = 0; i < num_adds; ++i) {
  11534. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  11535. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  11536. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  11537. next_node->type != GGML_TYPE_F32 ||
  11538. next_node->src[0]->type != GGML_TYPE_F32 ||
  11539. next_node->src[1]->type != GGML_TYPE_F32 ||
  11540. get_misalign_bytes(ctx, next_node) ||
  11541. get_misalign_bytes(ctx, next_node->src[0]) ||
  11542. get_misalign_bytes(ctx, next_node->src[1])) {
  11543. num_adds = i;
  11544. }
  11545. }
  11546. // Verify we can fuse these
  11547. ggml_op adds[MAX_FUSED_ADDS];
  11548. for (int32_t i = 0; i < num_adds; ++i) {
  11549. adds[i] = GGML_OP_ADD;
  11550. }
  11551. // decrease num_adds if they can't all be fused
  11552. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  11553. num_adds--;
  11554. }
  11555. // a single add is not "fused", so just return zero
  11556. if (num_adds == 1) {
  11557. return 0;
  11558. }
  11559. return num_adds;
  11560. }
  11561. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  11562. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  11563. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11564. if (vk_instance.debug_utils_support) {
  11565. vk::DebugUtilsLabelEXT dul = {};
  11566. dul.pLabelName = "ggml_backend_vk_graph_compute";
  11567. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  11568. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  11569. }
  11570. ctx->prealloc_size_add_rms_partials_offset = 0;
  11571. ctx->do_add_rms_partials = false;
  11572. ctx->do_add_rms_partials_offset_calculation = false;
  11573. int last_node = cgraph->n_nodes - 1;
  11574. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  11575. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  11576. last_node -= 1;
  11577. }
  11578. // Reserve tensor context space for all nodes
  11579. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  11580. bool first_node_in_batch = true; // true if next node will be first node in a batch
  11581. int submit_node_idx = 0; // index to first node in a batch
  11582. vk_context compute_ctx;
  11583. if (vk_perf_logger_enabled) {
  11584. // allocate/resize the query pool
  11585. if (ctx->num_queries < cgraph->n_nodes + 1) {
  11586. if (ctx->query_pool) {
  11587. ctx->device->device.destroyQueryPool(ctx->query_pool);
  11588. }
  11589. vk::QueryPoolCreateInfo query_create_info;
  11590. query_create_info.queryType = vk::QueryType::eTimestamp;
  11591. query_create_info.queryCount = cgraph->n_nodes + 100;
  11592. ctx->query_pool = ctx->device->device.createQueryPool(query_create_info);
  11593. ctx->num_queries = query_create_info.queryCount;
  11594. ctx->query_fusion_names.resize(ctx->num_queries);
  11595. ctx->query_fusion_node_count.resize(ctx->num_queries);
  11596. ctx->query_nodes.resize(ctx->num_queries);
  11597. ctx->query_node_idx.resize(ctx->num_queries);
  11598. }
  11599. ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1);
  11600. std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr);
  11601. std::fill(ctx->query_fusion_node_count.begin(), ctx->query_fusion_node_count.end(), 0);
  11602. std::fill(ctx->query_nodes.begin(), ctx->query_nodes.end(), nullptr);
  11603. std::fill(ctx->query_node_idx.begin(), ctx->query_node_idx.end(), 0);
  11604. GGML_ASSERT(ctx->compute_ctx.expired());
  11605. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11606. ctx->compute_ctx = compute_ctx;
  11607. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11608. ctx->query_idx = 0;
  11609. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11610. }
  11611. ctx->prealloc_y_last_pipeline_used = nullptr;
  11612. ctx->prealloc_y_last_tensor_used = nullptr;
  11613. if (ctx->prealloc_size_add_rms_partials) {
  11614. ggml_vk_preallocate_buffers(ctx, nullptr);
  11615. if (ctx->compute_ctx.expired()) {
  11616. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11617. ctx->compute_ctx = compute_ctx;
  11618. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11619. } else {
  11620. compute_ctx = ctx->compute_ctx.lock();
  11621. }
  11622. // initialize partial sums to zero.
  11623. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  11624. ggml_vk_sync_buffers(ctx, compute_ctx);
  11625. }
  11626. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  11627. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  11628. // (and scaled down based on model size, so smaller models submit earlier).
  11629. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  11630. int nodes_per_submit = 100;
  11631. int submitted_nodes = 0;
  11632. int submit_count = 0;
  11633. uint64_t mul_mat_bytes = 0;
  11634. uint64_t total_mul_mat_bytes = 0;
  11635. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  11636. for (int i = 0; i < cgraph->n_nodes; i++) {
  11637. if (first_node_in_batch) {
  11638. submit_node_idx = i;
  11639. }
  11640. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11641. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  11642. mul_mat_bytes += bytes;
  11643. total_mul_mat_bytes += bytes;
  11644. }
  11645. ctx->fused_topk_moe_mode = TOPK_MOE_COUNT;
  11646. ctx->fused_topk_moe_scale = false;
  11647. const char *fusion_string {};
  11648. if (!ctx->device->disable_fusion) {
  11649. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11650. if (num_adds) {
  11651. ctx->num_additional_fused_ops = num_adds - 1;
  11652. fusion_string = "MULTI_ADD";
  11653. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) {
  11654. ctx->num_additional_fused_ops = 2;
  11655. fusion_string = "MUL_MAT_ADD_ADD";
  11656. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11657. ctx->num_additional_fused_ops = 1;
  11658. fusion_string = "MUL_MAT_ADD";
  11659. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) {
  11660. ctx->num_additional_fused_ops = 2;
  11661. fusion_string = "MUL_MAT_ID_ADD_ID_MUL";
  11662. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11663. ctx->num_additional_fused_ops = 1;
  11664. fusion_string = "MUL_MAT_ID_ADD_ID";
  11665. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  11666. ctx->num_additional_fused_ops = 1;
  11667. fusion_string = "MUL_MAT_ID_MUL";
  11668. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 4 }) &&
  11669. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  11670. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  11671. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  11672. ctx->num_additional_fused_ops = 4;
  11673. fusion_string = "RMS_NORM_MUL_ROPE_VIEW_SET_ROWS";
  11674. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  11675. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  11676. ctx->num_additional_fused_ops = 2;
  11677. fusion_string = "RMS_NORM_MUL_ROPE";
  11678. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11679. ctx->num_additional_fused_ops = 1;
  11680. fusion_string = "RMS_NORM_MUL";
  11681. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11682. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11683. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11684. ctx->num_additional_fused_ops = 2;
  11685. fusion_string = "ROPE_VIEW_SET_ROWS";
  11686. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11687. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11688. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11689. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11690. // view of argsort writes to memory
  11691. ctx->fused_ops_write_mask |= 1 << 3;
  11692. ctx->fused_topk_moe_mode = TOPK_MOE_EARLY_SOFTMAX_NORM;
  11693. fusion_string = "TOPK_MOE_EARLY_SOFTMAX_NORM";
  11694. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_sigmoid_norm_bias, { i + 4, i + 10 }) &&
  11695. ggml_check_edges(cgraph, i, topk_moe_sigmoid_norm_bias_edges) &&
  11696. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_SIGMOID_NORM_BIAS)) {
  11697. ctx->num_additional_fused_ops = topk_moe_sigmoid_norm_bias.size() - 1;
  11698. // view of argsort writes to memory
  11699. ctx->fused_ops_write_mask |= 1 << 4;
  11700. ctx->fused_topk_moe_mode = TOPK_MOE_SIGMOID_NORM_BIAS;
  11701. fusion_string = "TOPK_MOE_SIGMOID_NORM_BIAS";
  11702. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11703. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11704. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11705. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11706. // view of argsort writes to memory
  11707. ctx->fused_ops_write_mask |= 1 << 3;
  11708. ctx->fused_topk_moe_mode = TOPK_MOE_EARLY_SOFTMAX;
  11709. fusion_string = "TOPK_MOE_EARLY_SOFTMAX";
  11710. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11711. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11712. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11713. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11714. // view of argsort writes to memory
  11715. ctx->fused_ops_write_mask |= 1 << 1;
  11716. ctx->fused_topk_moe_mode = TOPK_MOE_LATE_SOFTMAX;
  11717. fusion_string = "TOPK_MOE_LATE_SOFTMAX";
  11718. }
  11719. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  11720. // Look for an additional scale op to fuse - occurs in deepseek2 and nemotron3 nano.
  11721. if (ggml_can_fuse_subgraph(cgraph, i + ctx->num_additional_fused_ops - 1, { GGML_OP_DIV, GGML_OP_RESHAPE, GGML_OP_SCALE }, { i + ctx->num_additional_fused_ops + 1 }) ||
  11722. ggml_can_fuse_subgraph(cgraph, i + ctx->num_additional_fused_ops, { GGML_OP_GET_ROWS, GGML_OP_SCALE }, { i + ctx->num_additional_fused_ops + 1 })) {
  11723. ctx->fused_topk_moe_scale = true;
  11724. ctx->num_additional_fused_ops++;
  11725. }
  11726. }
  11727. }
  11728. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  11729. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  11730. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  11731. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11732. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11733. (i + ctx->num_additional_fused_ops >= last_node) ||
  11734. (almost_ready && !ctx->almost_ready_fence_pending);
  11735. bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, i + ctx->num_additional_fused_ops >= last_node, almost_ready, submit);
  11736. if (vk_perf_logger_enabled && enqueued) {
  11737. if (ctx->compute_ctx.expired()) {
  11738. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11739. ctx->compute_ctx = compute_ctx;
  11740. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11741. } else {
  11742. compute_ctx = ctx->compute_ctx.lock();
  11743. }
  11744. if (!vk_perf_logger_concurrent) {
  11745. // track a single node/fusion for the current query
  11746. ctx->query_nodes[ctx->query_idx] = cgraph->nodes[i];
  11747. ctx->query_fusion_names[ctx->query_idx] = fusion_string;
  11748. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11749. } else {
  11750. // track a fusion string and number of fused ops for the current node_idx
  11751. ctx->query_fusion_names[i] = fusion_string;
  11752. ctx->query_fusion_node_count[i] = ctx->num_additional_fused_ops;
  11753. }
  11754. }
  11755. if (enqueued) {
  11756. ++submitted_nodes;
  11757. #ifndef GGML_VULKAN_CHECK_RESULTS
  11758. if (first_node_in_batch) {
  11759. first_node_in_batch = false;
  11760. }
  11761. #endif
  11762. }
  11763. if (submit && enqueued) {
  11764. first_node_in_batch = true;
  11765. submitted_nodes = 0;
  11766. mul_mat_bytes = 0;
  11767. if (submit_count < 3) {
  11768. mul_mat_bytes_per_submit *= 2;
  11769. }
  11770. submit_count++;
  11771. }
  11772. i += ctx->num_additional_fused_ops;
  11773. ctx->num_additional_fused_ops = 0;
  11774. ctx->fused_ops_write_mask = 0;
  11775. }
  11776. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11777. if (vk_perf_logger_enabled) {
  11778. // End the command buffer and submit/wait
  11779. GGML_ASSERT(!ctx->compute_ctx.expired());
  11780. compute_ctx = ctx->compute_ctx.lock();
  11781. ggml_vk_ctx_end(compute_ctx);
  11782. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11783. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11784. ctx->device->device.resetFences({ ctx->device->fence });
  11785. // Get the results and pass them to the logger
  11786. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11787. VK_CHECK(ctx->device->device.getQueryPoolResults(ctx->query_pool, 0, ctx->query_idx, (cgraph->n_nodes + 1)*sizeof(uint64_t), timestamps.data(), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait), "get timestamp results");
  11788. if (!vk_perf_logger_concurrent) {
  11789. // Log each op separately
  11790. for (int i = 1; i < ctx->query_idx; i++) {
  11791. auto node = ctx->query_nodes[i];
  11792. auto name = ctx->query_fusion_names[i];
  11793. ctx->perf_logger->log_timing(node, name, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11794. }
  11795. } else {
  11796. // Log each group of nodes
  11797. int prev_node_idx = 0;
  11798. for (int i = 1; i < ctx->query_idx; i++) {
  11799. auto cur_node_idx = ctx->query_node_idx[i];
  11800. std::vector<ggml_tensor *> nodes;
  11801. std::vector<const char *> names;
  11802. for (int node_idx = prev_node_idx; node_idx < cur_node_idx; ++node_idx) {
  11803. if (ggml_op_is_empty(cgraph->nodes[node_idx]->op)) {
  11804. continue;
  11805. }
  11806. nodes.push_back(cgraph->nodes[node_idx]);
  11807. names.push_back(ctx->query_fusion_names[node_idx]);
  11808. node_idx += ctx->query_fusion_node_count[node_idx];
  11809. }
  11810. prev_node_idx = cur_node_idx;
  11811. ctx->perf_logger->log_timing(nodes, names, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11812. }
  11813. }
  11814. ctx->perf_logger->print_timings();
  11815. }
  11816. if (!ctx->device->support_async) {
  11817. ggml_vk_synchronize(ctx);
  11818. }
  11819. return GGML_STATUS_SUCCESS;
  11820. UNUSED(backend);
  11821. }
  11822. // Sort the graph for improved parallelism.
  11823. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11824. {
  11825. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11826. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11827. if (ctx->device->disable_graph_optimize) {
  11828. return;
  11829. }
  11830. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11831. return 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;
  11832. };
  11833. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11834. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11835. if (dst->src[s] == src) {
  11836. return true;
  11837. }
  11838. }
  11839. // implicit dependency if they view the same tensor
  11840. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11841. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11842. if (dst2 == src2) {
  11843. return true;
  11844. }
  11845. return false;
  11846. };
  11847. std::vector<ggml_tensor *> new_order;
  11848. std::vector<bool> used(graph->n_nodes, false);
  11849. std::set<ggml_tensor *> used_node_set;
  11850. int first_unused = 0;
  11851. while (first_unused < graph->n_nodes) {
  11852. std::vector<int> current_set;
  11853. // Check for fusion patterns and avoid reordering them
  11854. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11855. if (start + (int)pattern.size() <= graph->n_nodes) {
  11856. bool is_pattern = true;
  11857. for (size_t j = 0; j < pattern.size(); ++j) {
  11858. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11859. is_pattern = false;
  11860. }
  11861. }
  11862. return is_pattern;
  11863. }
  11864. return false;
  11865. };
  11866. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11867. if (match_pattern(pattern, first_unused)) {
  11868. for (size_t j = 0; j < pattern.size(); ++j) {
  11869. new_order.push_back(graph->nodes[first_unused + j]);
  11870. used_node_set.insert(graph->nodes[first_unused + j]);
  11871. used[first_unused + j] = true;
  11872. }
  11873. while (first_unused < graph->n_nodes && used[first_unused]) {
  11874. first_unused++;
  11875. }
  11876. return true;
  11877. }
  11878. return false;
  11879. };
  11880. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11881. continue;
  11882. }
  11883. if (keep_pattern(topk_moe_sigmoid_norm_bias)) {
  11884. continue;
  11885. }
  11886. if (keep_pattern(topk_moe_early_softmax)) {
  11887. continue;
  11888. }
  11889. if (keep_pattern(topk_moe_late_softmax)) {
  11890. continue;
  11891. }
  11892. // First, grab the next unused node.
  11893. current_set.push_back(first_unused);
  11894. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11895. // haven't already been run. Nodes that have already been run have used[i] set
  11896. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11897. // that we support (e.g. RMS_NORM + MUL).
  11898. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11899. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11900. const int NUM_TO_CHECK = 20;
  11901. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11902. if (used[j]) {
  11903. continue;
  11904. }
  11905. if (is_empty(graph->nodes[j])) {
  11906. continue;
  11907. }
  11908. // Don't pull forward nodes from fusion patterns
  11909. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11910. match_pattern(topk_moe_sigmoid_norm_bias, j) ||
  11911. match_pattern(topk_moe_early_softmax, j) ||
  11912. match_pattern(topk_moe_late_softmax, j)) {
  11913. continue;
  11914. }
  11915. bool ok = true;
  11916. for (int c = first_unused; c < j; ++c) {
  11917. if (!used[c] &&
  11918. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11919. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11920. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11921. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11922. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL) &&
  11923. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_ADD && graph->nodes[j]->op == GGML_OP_ADD)) {
  11924. ok = false;
  11925. break;
  11926. }
  11927. }
  11928. if (ok) {
  11929. current_set.push_back(j);
  11930. int rope_idx = j;
  11931. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11932. if (j > 0 &&
  11933. graph->nodes[j]->op == GGML_OP_MUL &&
  11934. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11935. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11936. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11937. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11938. // Check that other srcs are already valid
  11939. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11940. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11941. rope_idx = k;
  11942. current_set.push_back(rope_idx);
  11943. used[rope_idx] = true;
  11944. break;
  11945. }
  11946. }
  11947. }
  11948. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11949. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11950. int view_idx = -1;
  11951. int set_rows_idx = -1;
  11952. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11953. if (view_idx == -1 &&
  11954. graph->nodes[k]->op == GGML_OP_VIEW &&
  11955. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11956. view_idx = k;
  11957. continue;
  11958. }
  11959. if (view_idx != -1 &&
  11960. set_rows_idx == -1 &&
  11961. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11962. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11963. set_rows_idx = k;
  11964. break;
  11965. }
  11966. }
  11967. if (set_rows_idx != -1) {
  11968. current_set.push_back(view_idx);
  11969. current_set.push_back(set_rows_idx);
  11970. used[view_idx] = true;
  11971. used[set_rows_idx] = true;
  11972. }
  11973. }
  11974. // Look for MUL_MAT_ID + ADD_ID + MUL
  11975. if (j > 0 &&
  11976. graph->nodes[j]->op == GGML_OP_ADD_ID &&
  11977. graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) {
  11978. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11979. if (graph->nodes[k]->op == GGML_OP_MUL &&
  11980. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11981. // src1 must either be weights or already processed
  11982. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11983. current_set.push_back(k);
  11984. used[k] = true;
  11985. break;
  11986. }
  11987. }
  11988. }
  11989. // Look for MUL_MAT + ADD + ADD
  11990. if (j > 0 &&
  11991. graph->nodes[j]->op == GGML_OP_ADD &&
  11992. graph->nodes[j-1]->op == GGML_OP_MUL_MAT) {
  11993. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11994. if (graph->nodes[k]->op == GGML_OP_ADD &&
  11995. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11996. // src1 must either be weights or already processed
  11997. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11998. current_set.push_back(k);
  11999. used[k] = true;
  12000. break;
  12001. }
  12002. }
  12003. }
  12004. }
  12005. }
  12006. // Second pass grabs view nodes.
  12007. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  12008. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  12009. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  12010. if (used[j]) {
  12011. continue;
  12012. }
  12013. if (!is_empty(graph->nodes[j])) {
  12014. continue;
  12015. }
  12016. bool ok = true;
  12017. for (int c = first_unused; c < j; ++c) {
  12018. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  12019. // skip views whose srcs haven't been processed.
  12020. if (!used[c] &&
  12021. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  12022. !c_in_current_set) {
  12023. ok = false;
  12024. break;
  12025. }
  12026. }
  12027. if (ok) {
  12028. current_set.push_back(j);
  12029. }
  12030. }
  12031. }
  12032. // Push the current set into new_order
  12033. for (auto c : current_set) {
  12034. new_order.push_back(graph->nodes[c]);
  12035. used_node_set.insert(graph->nodes[c]);
  12036. used[c] = true;
  12037. }
  12038. while (first_unused < graph->n_nodes && used[first_unused]) {
  12039. first_unused++;
  12040. }
  12041. }
  12042. // Replace the graph with the new order.
  12043. for (int i = 0; i < graph->n_nodes; ++i) {
  12044. graph->nodes[i] = new_order[i];
  12045. }
  12046. }
  12047. static void ggml_backend_vk_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
  12048. VK_LOG_DEBUG("ggml_backend_vk_event_record(backend=" << backend << ", event=" << event << ")");
  12049. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  12050. vk_event *vkev = (vk_event *)event->context;
  12051. vk_context transfer_ctx;
  12052. if (ctx->transfer_ctx.expired()) {
  12053. // Initialize new transfer context
  12054. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  12055. ctx->transfer_ctx = transfer_ctx;
  12056. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  12057. } else {
  12058. transfer_ctx = ctx->transfer_ctx.lock();
  12059. }
  12060. // the backend interface doesn't have an explicit reset, so reset it here
  12061. // before we record the command to set it
  12062. ctx->device->device.resetEvent(vkev->event);
  12063. ctx->device->device.resetFences({ vkev->fence });
  12064. ggml_vk_set_event(transfer_ctx, vkev->event);
  12065. ggml_vk_ctx_end(transfer_ctx);
  12066. ggml_vk_submit(transfer_ctx, {vkev->fence});
  12067. ctx->submit_pending = true;
  12068. ctx->transfer_ctx.reset();
  12069. }
  12070. static void ggml_backend_vk_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
  12071. VK_LOG_DEBUG("ggml_backend_vk_event_wait(backend=" << backend << ", event=" << event << ")");
  12072. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  12073. vk_event *vkev = (vk_event *)event->context;
  12074. vk_context transfer_ctx;
  12075. if (ctx->transfer_ctx.expired()) {
  12076. // Initialize new transfer context
  12077. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  12078. ctx->transfer_ctx = transfer_ctx;
  12079. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  12080. } else {
  12081. transfer_ctx = ctx->transfer_ctx.lock();
  12082. }
  12083. ggml_vk_wait_events(transfer_ctx, {vkev->event});
  12084. ggml_vk_ctx_end(transfer_ctx);
  12085. ctx->transfer_ctx.reset();
  12086. }
  12087. // TODO: enable async and synchronize
  12088. static ggml_backend_i ggml_backend_vk_interface = {
  12089. /* .get_name = */ ggml_backend_vk_name,
  12090. /* .free = */ ggml_backend_vk_free,
  12091. /* .set_tensor_async = */ ggml_backend_vk_set_tensor_async,
  12092. /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async,
  12093. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  12094. /* .synchronize = */ ggml_backend_vk_synchronize,
  12095. /* .graph_plan_create = */ NULL,
  12096. /* .graph_plan_free = */ NULL,
  12097. /* .graph_plan_update = */ NULL,
  12098. /* .graph_plan_compute = */ NULL,
  12099. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  12100. /* .event_record = */ ggml_backend_vk_event_record,
  12101. /* .event_wait = */ ggml_backend_vk_event_wait,
  12102. /* .graph_optimize = */ ggml_vk_graph_optimize,
  12103. };
  12104. static ggml_guid_t ggml_backend_vk_guid() {
  12105. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  12106. return &guid;
  12107. }
  12108. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  12109. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  12110. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  12111. ggml_vk_init(ctx, dev_num);
  12112. ggml_backend_t vk_backend = new ggml_backend {
  12113. /* .guid = */ ggml_backend_vk_guid(),
  12114. /* .iface = */ ggml_backend_vk_interface,
  12115. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  12116. /* .context = */ ctx,
  12117. };
  12118. if (!ctx->device->support_async) {
  12119. vk_backend->iface.get_tensor_async = nullptr;
  12120. }
  12121. return vk_backend;
  12122. }
  12123. bool ggml_backend_is_vk(ggml_backend_t backend) {
  12124. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  12125. }
  12126. int ggml_backend_vk_get_device_count() {
  12127. return ggml_vk_get_device_count();
  12128. }
  12129. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  12130. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  12131. int dev_idx = vk_instance.device_indices[device];
  12132. ggml_vk_get_device_description(dev_idx, description, description_size);
  12133. }
  12134. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  12135. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  12136. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  12137. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  12138. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  12139. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  12140. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  12141. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  12142. if (membudget_supported) {
  12143. memprops.pNext = &budgetprops;
  12144. }
  12145. vkdev.getMemoryProperties2(&memprops);
  12146. *total = 0;
  12147. *free = 0;
  12148. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  12149. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  12150. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  12151. *total += heap.size;
  12152. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  12153. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  12154. } else {
  12155. *free += heap.size;
  12156. }
  12157. }
  12158. }
  12159. }
  12160. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  12161. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  12162. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  12163. vk::PhysicalDeviceProperties2 props = {};
  12164. device.getProperties2(&props);
  12165. return props.properties.deviceType;
  12166. }
  12167. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  12168. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  12169. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  12170. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  12171. bool ext_support = false;
  12172. for (const auto& properties : ext_props) {
  12173. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  12174. ext_support = true;
  12175. break;
  12176. }
  12177. }
  12178. if (!ext_support) {
  12179. return "";
  12180. }
  12181. vk::PhysicalDeviceProperties2 props = {};
  12182. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  12183. props.pNext = &pci_bus_info;
  12184. device.getProperties2(&props);
  12185. const uint32_t pci_domain = pci_bus_info.pciDomain;
  12186. const uint32_t pci_bus = pci_bus_info.pciBus;
  12187. const uint32_t pci_device = pci_bus_info.pciDevice;
  12188. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  12189. char pci_bus_id[16] = {};
  12190. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  12191. return std::string(pci_bus_id);
  12192. }
  12193. //////////////////////////
  12194. struct ggml_backend_vk_device_context {
  12195. size_t device;
  12196. std::string name;
  12197. std::string description;
  12198. bool is_integrated_gpu;
  12199. std::string pci_bus_id;
  12200. int op_offload_min_batch_size;
  12201. };
  12202. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  12203. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12204. return ctx->name.c_str();
  12205. }
  12206. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  12207. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12208. return ctx->description.c_str();
  12209. }
  12210. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  12211. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  12212. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  12213. }
  12214. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  12215. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12216. return ggml_backend_vk_buffer_type(ctx->device);
  12217. }
  12218. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  12219. UNUSED(dev);
  12220. return ggml_backend_vk_host_buffer_type();
  12221. }
  12222. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  12223. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12224. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  12225. }
  12226. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  12227. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12228. props->name = ggml_backend_vk_device_get_name(dev);
  12229. props->description = ggml_backend_vk_device_get_description(dev);
  12230. props->type = ggml_backend_vk_device_get_type(dev);
  12231. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  12232. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  12233. props->caps = {
  12234. /* .async = */ true,
  12235. /* .host_buffer = */ true,
  12236. /* .buffer_from_host_ptr = */ false,
  12237. /* .events = */ true,
  12238. };
  12239. }
  12240. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  12241. UNUSED(params);
  12242. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12243. return ggml_backend_vk_init(ctx->device);
  12244. }
  12245. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12246. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12247. const vk_device& device = ggml_vk_get_device(ctx->device);
  12248. // reject any tensors larger than the max buffer size
  12249. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12250. if (op->src[i] && ggml_nbytes(op->src[i]) > device->max_buffer_size) {
  12251. return false;
  12252. }
  12253. }
  12254. if (ggml_nbytes(op) > device->max_buffer_size) {
  12255. return false;
  12256. }
  12257. switch (op->op) {
  12258. case GGML_OP_UNARY:
  12259. switch (ggml_get_unary_op(op)) {
  12260. case GGML_UNARY_OP_EXP:
  12261. case GGML_UNARY_OP_GELU:
  12262. case GGML_UNARY_OP_GELU_ERF:
  12263. case GGML_UNARY_OP_GELU_QUICK:
  12264. case GGML_UNARY_OP_SILU:
  12265. case GGML_UNARY_OP_RELU:
  12266. case GGML_UNARY_OP_XIELU:
  12267. case GGML_UNARY_OP_NEG:
  12268. case GGML_UNARY_OP_TANH:
  12269. case GGML_UNARY_OP_SIGMOID:
  12270. case GGML_UNARY_OP_HARDSIGMOID:
  12271. case GGML_UNARY_OP_HARDSWISH:
  12272. case GGML_UNARY_OP_ABS:
  12273. case GGML_UNARY_OP_SOFTPLUS:
  12274. case GGML_UNARY_OP_STEP:
  12275. case GGML_UNARY_OP_ROUND:
  12276. case GGML_UNARY_OP_CEIL:
  12277. case GGML_UNARY_OP_FLOOR:
  12278. case GGML_UNARY_OP_TRUNC:
  12279. return ggml_is_contiguous(op->src[0]) &&
  12280. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12281. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  12282. (op->src[0]->type == op->type);
  12283. default:
  12284. return false;
  12285. }
  12286. case GGML_OP_GLU:
  12287. switch (ggml_get_glu_op(op)) {
  12288. case GGML_GLU_OP_GEGLU:
  12289. case GGML_GLU_OP_REGLU:
  12290. case GGML_GLU_OP_SWIGLU:
  12291. case GGML_GLU_OP_SWIGLU_OAI:
  12292. case GGML_GLU_OP_GEGLU_ERF:
  12293. case GGML_GLU_OP_GEGLU_QUICK:
  12294. return ggml_is_contiguous(op->src[0]) &&
  12295. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12296. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  12297. (op->src[0]->type == op->type);
  12298. default:
  12299. return false;
  12300. }
  12301. case GGML_OP_MUL_MAT:
  12302. case GGML_OP_MUL_MAT_ID:
  12303. {
  12304. ggml_type src0_type = op->src[0]->type;
  12305. if (op->op == GGML_OP_MUL_MAT_ID) {
  12306. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  12307. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  12308. return false;
  12309. }
  12310. }
  12311. switch (src0_type) {
  12312. case GGML_TYPE_F32:
  12313. case GGML_TYPE_F16:
  12314. case GGML_TYPE_BF16:
  12315. case GGML_TYPE_Q4_0:
  12316. case GGML_TYPE_Q4_1:
  12317. case GGML_TYPE_Q5_0:
  12318. case GGML_TYPE_Q5_1:
  12319. case GGML_TYPE_Q8_0:
  12320. case GGML_TYPE_Q2_K:
  12321. case GGML_TYPE_Q3_K:
  12322. case GGML_TYPE_Q4_K:
  12323. case GGML_TYPE_Q5_K:
  12324. case GGML_TYPE_Q6_K:
  12325. case GGML_TYPE_IQ1_S:
  12326. case GGML_TYPE_IQ1_M:
  12327. case GGML_TYPE_IQ2_XXS:
  12328. case GGML_TYPE_IQ2_XS:
  12329. case GGML_TYPE_IQ2_S:
  12330. case GGML_TYPE_IQ3_XXS:
  12331. case GGML_TYPE_IQ3_S:
  12332. case GGML_TYPE_IQ4_XS:
  12333. case GGML_TYPE_IQ4_NL:
  12334. case GGML_TYPE_MXFP4:
  12335. break;
  12336. default:
  12337. return false;
  12338. }
  12339. struct ggml_tensor * a;
  12340. struct ggml_tensor * b;
  12341. if (op->op == GGML_OP_MUL_MAT) {
  12342. a = op->src[0];
  12343. b = op->src[1];
  12344. } else {
  12345. a = op->src[2];
  12346. b = op->src[1];
  12347. }
  12348. if (a->ne[3] != b->ne[3]) {
  12349. return false;
  12350. }
  12351. if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) ||
  12352. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  12353. return false;
  12354. }
  12355. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  12356. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  12357. // So don't support this combination for now.
  12358. return false;
  12359. }
  12360. return true;
  12361. }
  12362. case GGML_OP_FLASH_ATTN_EXT:
  12363. {
  12364. bool coopmat2 = device->coopmat2;
  12365. uint32_t HSK = op->src[1]->ne[0];
  12366. uint32_t HSV = op->src[2]->ne[0];
  12367. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  12368. return false;
  12369. }
  12370. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  12371. return false;
  12372. }
  12373. if (op->src[0]->type != GGML_TYPE_F32) {
  12374. return false;
  12375. }
  12376. if (op->type != GGML_TYPE_F32) {
  12377. return false;
  12378. }
  12379. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  12380. return false;
  12381. }
  12382. // It's straightforward to support different K/V dequant, but would
  12383. // significantly increase the number of pipelines
  12384. if (op->src[1]->type != op->src[2]->type) {
  12385. return false;
  12386. }
  12387. switch (op->src[1]->type) {
  12388. case GGML_TYPE_F16:
  12389. case GGML_TYPE_F32:
  12390. case GGML_TYPE_Q4_0:
  12391. case GGML_TYPE_Q8_0:
  12392. // supported in scalar and coopmat2 paths
  12393. break;
  12394. case GGML_TYPE_Q4_1:
  12395. case GGML_TYPE_Q5_0:
  12396. case GGML_TYPE_Q5_1:
  12397. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  12398. //case GGML_TYPE_Q2_K:
  12399. //case GGML_TYPE_Q3_K:
  12400. //case GGML_TYPE_Q4_K:
  12401. //case GGML_TYPE_Q5_K:
  12402. //case GGML_TYPE_Q6_K:
  12403. //case GGML_TYPE_IQ1_S:
  12404. //case GGML_TYPE_IQ1_M:
  12405. //case GGML_TYPE_IQ2_XXS:
  12406. //case GGML_TYPE_IQ2_XS:
  12407. //case GGML_TYPE_IQ2_S:
  12408. //case GGML_TYPE_IQ3_XXS:
  12409. //case GGML_TYPE_IQ3_S:
  12410. //case GGML_TYPE_IQ4_XS:
  12411. case GGML_TYPE_IQ4_NL:
  12412. // currently supported only in coopmat2 path
  12413. if (!coopmat2) {
  12414. return false;
  12415. }
  12416. break;
  12417. default:
  12418. return false;
  12419. }
  12420. if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) {
  12421. // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll
  12422. return false;
  12423. }
  12424. return true;
  12425. }
  12426. case GGML_OP_GET_ROWS:
  12427. {
  12428. switch (op->src[0]->type) {
  12429. case GGML_TYPE_F32:
  12430. case GGML_TYPE_F16:
  12431. case GGML_TYPE_BF16:
  12432. case GGML_TYPE_Q4_0:
  12433. case GGML_TYPE_Q4_1:
  12434. case GGML_TYPE_Q5_0:
  12435. case GGML_TYPE_Q5_1:
  12436. case GGML_TYPE_Q8_0:
  12437. case GGML_TYPE_Q2_K:
  12438. case GGML_TYPE_Q3_K:
  12439. case GGML_TYPE_Q4_K:
  12440. case GGML_TYPE_Q5_K:
  12441. case GGML_TYPE_Q6_K:
  12442. case GGML_TYPE_IQ1_S:
  12443. case GGML_TYPE_IQ1_M:
  12444. case GGML_TYPE_IQ2_XXS:
  12445. case GGML_TYPE_IQ2_XS:
  12446. case GGML_TYPE_IQ2_S:
  12447. case GGML_TYPE_IQ3_XXS:
  12448. case GGML_TYPE_IQ3_S:
  12449. case GGML_TYPE_IQ4_XS:
  12450. case GGML_TYPE_IQ4_NL:
  12451. case GGML_TYPE_MXFP4:
  12452. case GGML_TYPE_I32:
  12453. return true;
  12454. default:
  12455. return false;
  12456. }
  12457. }
  12458. case GGML_OP_SET_ROWS:
  12459. {
  12460. switch (op->type) {
  12461. case GGML_TYPE_F32:
  12462. case GGML_TYPE_F16:
  12463. case GGML_TYPE_BF16:
  12464. case GGML_TYPE_Q4_0:
  12465. case GGML_TYPE_Q4_1:
  12466. case GGML_TYPE_Q5_0:
  12467. case GGML_TYPE_Q5_1:
  12468. case GGML_TYPE_Q8_0:
  12469. case GGML_TYPE_IQ4_NL:
  12470. return true;
  12471. default:
  12472. return false;
  12473. }
  12474. }
  12475. case GGML_OP_CONT:
  12476. case GGML_OP_CPY:
  12477. case GGML_OP_DUP:
  12478. {
  12479. ggml_type src0_type = op->src[0]->type;
  12480. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  12481. if (src0_type == GGML_TYPE_F32) {
  12482. switch (src1_type) {
  12483. case GGML_TYPE_F32:
  12484. case GGML_TYPE_F16:
  12485. case GGML_TYPE_BF16:
  12486. case GGML_TYPE_Q4_0:
  12487. case GGML_TYPE_Q4_1:
  12488. case GGML_TYPE_Q5_0:
  12489. case GGML_TYPE_Q5_1:
  12490. case GGML_TYPE_Q8_0:
  12491. case GGML_TYPE_IQ4_NL:
  12492. return true;
  12493. default:
  12494. break;
  12495. }
  12496. }
  12497. if (src1_type == GGML_TYPE_F32) {
  12498. switch (src0_type) {
  12499. case GGML_TYPE_F16:
  12500. case GGML_TYPE_Q4_0:
  12501. case GGML_TYPE_Q4_1:
  12502. case GGML_TYPE_Q5_0:
  12503. case GGML_TYPE_Q5_1:
  12504. case GGML_TYPE_Q8_0:
  12505. case GGML_TYPE_IQ4_NL:
  12506. return true;
  12507. default:
  12508. break;
  12509. }
  12510. }
  12511. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  12512. return true;
  12513. }
  12514. if (
  12515. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  12516. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  12517. ) {
  12518. return true;
  12519. }
  12520. // We can handle copying from a type to the same type if it's
  12521. // either not quantized or is quantized and contiguous.
  12522. // We use f16 or f32 shaders to do the copy,
  12523. // so the type/block size must be a multiple of 4.
  12524. if (src0_type == src1_type &&
  12525. (!ggml_is_quantized(src0_type) || (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op))) &&
  12526. (ggml_type_size(src0_type) % 2) == 0) {
  12527. return true;
  12528. }
  12529. return false;
  12530. }
  12531. case GGML_OP_REPEAT:
  12532. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  12533. case GGML_OP_REPEAT_BACK:
  12534. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  12535. case GGML_OP_ROPE:
  12536. case GGML_OP_ROPE_BACK:
  12537. case GGML_OP_NONE:
  12538. case GGML_OP_RESHAPE:
  12539. case GGML_OP_VIEW:
  12540. case GGML_OP_PERMUTE:
  12541. case GGML_OP_TRANSPOSE:
  12542. case GGML_OP_RMS_NORM:
  12543. return true;
  12544. case GGML_OP_NORM:
  12545. case GGML_OP_GROUP_NORM:
  12546. case GGML_OP_L2_NORM:
  12547. return ggml_is_contiguous(op->src[0]);
  12548. case GGML_OP_ADD:
  12549. case GGML_OP_SUB:
  12550. case GGML_OP_MUL:
  12551. case GGML_OP_DIV:
  12552. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12553. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  12554. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12555. case GGML_OP_ADD_ID:
  12556. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  12557. op->type == GGML_TYPE_F32;
  12558. case GGML_OP_SILU_BACK:
  12559. case GGML_OP_RMS_NORM_BACK:
  12560. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12561. case GGML_OP_SQR:
  12562. case GGML_OP_SQRT:
  12563. case GGML_OP_SIN:
  12564. case GGML_OP_COS:
  12565. case GGML_OP_CLAMP:
  12566. return op->src[0]->type == GGML_TYPE_F32;
  12567. case GGML_OP_LEAKY_RELU:
  12568. case GGML_OP_OPT_STEP_ADAMW:
  12569. case GGML_OP_OPT_STEP_SGD:
  12570. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12571. case GGML_OP_LOG:
  12572. case GGML_OP_TRI:
  12573. case GGML_OP_DIAG:
  12574. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12575. op->type == op->src[0]->type;
  12576. case GGML_OP_ARGSORT:
  12577. {
  12578. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12579. return false;
  12580. }
  12581. // pipeline_argsort_large_f32 requires vulkan memory model.
  12582. if (device->vulkan_memory_model) {
  12583. return true;
  12584. } else {
  12585. return op->ne[0] <= (1 << device->max_workgroup_size_log2);
  12586. }
  12587. }
  12588. case GGML_OP_TOP_K:
  12589. {
  12590. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12591. return false;
  12592. }
  12593. // We could potentially support larger, using argsort to sort the
  12594. // whole thing. Not clear if this is needed.
  12595. uint32_t min_pipeline = (uint32_t)log2f(float(op->ne[0])) + 1;
  12596. if (min_pipeline >= num_topk_pipelines ||
  12597. !device->pipeline_topk_f32[min_pipeline]) {
  12598. return false;
  12599. }
  12600. }
  12601. return true;
  12602. case GGML_OP_UPSCALE:
  12603. if (op->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS) {
  12604. if ((op->op_params[0] & 0xFF) != GGML_SCALE_MODE_BILINEAR) {
  12605. return false;
  12606. }
  12607. }
  12608. return op->src[0]->type == GGML_TYPE_F32;
  12609. case GGML_OP_ACC:
  12610. return op->src[0]->type == GGML_TYPE_F32;
  12611. case GGML_OP_CONCAT:
  12612. return ggml_type_size(op->src[0]->type) == ggml_type_size(GGML_TYPE_F32);
  12613. case GGML_OP_ADD1:
  12614. return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32)
  12615. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32)
  12616. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16);
  12617. case GGML_OP_ARANGE:
  12618. case GGML_OP_FILL:
  12619. return op->type == GGML_TYPE_F32;
  12620. case GGML_OP_SCALE:
  12621. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12622. case GGML_OP_PAD:
  12623. case GGML_OP_ROLL:
  12624. return op->src[0]->type == GGML_TYPE_F32;
  12625. case GGML_OP_DIAG_MASK_INF:
  12626. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12627. case GGML_OP_SOFT_MAX:
  12628. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12629. && (!op->src[1] || (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16));
  12630. case GGML_OP_SOFT_MAX_BACK:
  12631. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12632. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32;
  12633. case GGML_OP_SUM:
  12634. case GGML_OP_SUM_ROWS:
  12635. case GGML_OP_MEAN:
  12636. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12637. case GGML_OP_CUMSUM:
  12638. {
  12639. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  12640. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12641. }
  12642. return false;
  12643. }
  12644. case GGML_OP_SOLVE_TRI:
  12645. {
  12646. if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32) {
  12647. return false;
  12648. }
  12649. const uint32_t N = op->src[0]->ne[0];
  12650. const uint32_t K = op->src[1]->ne[0];
  12651. // K dimension limited to workgroup size
  12652. if (K > 1u << device->max_workgroup_size_log2) {
  12653. return false;
  12654. }
  12655. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((N + K) * sizeof(float));
  12656. if (batch_N == 0) {
  12657. return false;
  12658. }
  12659. return true;
  12660. }
  12661. case GGML_OP_ARGMAX:
  12662. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12663. case GGML_OP_COUNT_EQUAL:
  12664. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_I32
  12665. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_I32;
  12666. case GGML_OP_IM2COL:
  12667. return ggml_is_contiguous(op->src[1])
  12668. && op->src[1]->type == GGML_TYPE_F32
  12669. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12670. case GGML_OP_IM2COL_3D:
  12671. return op->src[1]->type == GGML_TYPE_F32
  12672. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12673. case GGML_OP_TIMESTEP_EMBEDDING:
  12674. return op->src[0]->type == GGML_TYPE_F32;
  12675. case GGML_OP_CONV_2D_DW:
  12676. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16)
  12677. && op->src[1]->type == GGML_TYPE_F32;
  12678. case GGML_OP_POOL_2D:
  12679. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12680. case GGML_OP_RWKV_WKV6:
  12681. case GGML_OP_RWKV_WKV7:
  12682. return true; // all inputs are contiguous, see ggml.c
  12683. case GGML_OP_SSM_SCAN:
  12684. {
  12685. for (int i = 0; i < 6; i++) {
  12686. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  12687. return false;
  12688. }
  12689. }
  12690. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  12691. return false;
  12692. }
  12693. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  12694. return false;
  12695. }
  12696. const uint32_t d_state = op->src[0]->ne[0];
  12697. const uint32_t head_dim = op->src[0]->ne[1];
  12698. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  12699. if (!is_mamba2) {
  12700. return false;
  12701. }
  12702. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  12703. return false;
  12704. }
  12705. size_t shmem_size = d_state * sizeof(float);
  12706. if (shmem_size > device->properties.limits.maxComputeSharedMemorySize) {
  12707. return false;
  12708. }
  12709. if (!device->subgroup_basic) {
  12710. return false;
  12711. }
  12712. return true;
  12713. }
  12714. case GGML_OP_SSM_CONV:
  12715. return op->src[0]->type == GGML_TYPE_F32;
  12716. case GGML_OP_CONV_TRANSPOSE_1D:
  12717. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  12718. case GGML_OP_CONV_2D:
  12719. case GGML_OP_CONV_TRANSPOSE_2D:
  12720. {
  12721. // Channel-contiguous format is not supported yet.
  12722. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12723. op->src[1]->type == GGML_TYPE_F32 &&
  12724. op->type == GGML_TYPE_F32 &&
  12725. ggml_is_contiguous(op->src[0]) &&
  12726. ggml_is_contiguous(op->src[1]) &&
  12727. ggml_is_contiguous(op));
  12728. }
  12729. default:
  12730. return false;
  12731. }
  12732. UNUSED(dev);
  12733. }
  12734. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  12735. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  12736. return false;
  12737. }
  12738. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12739. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  12740. return buft_ctx->device->idx == ctx->device;
  12741. }
  12742. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12743. ggml_backend_vk_device_context * dev_ctx = (ggml_backend_vk_device_context *)dev->context;
  12744. return (op->ne[1] >= dev_ctx->op_offload_min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  12745. (op->ne[2] >= dev_ctx->op_offload_min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  12746. }
  12747. static ggml_backend_event_t ggml_backend_vk_device_event_new(ggml_backend_dev_t dev) {
  12748. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12749. auto device = ggml_vk_get_device(ctx->device);
  12750. vk_event *vkev = new vk_event;
  12751. if (!vkev) {
  12752. return nullptr;
  12753. }
  12754. // The event/fence is expected to initially be in the signaled state.
  12755. vkev->event = device->device.createEvent({});
  12756. vkev->fence = device->device.createFence({vk::FenceCreateFlagBits::eSignaled});
  12757. device->device.setEvent(vkev->event);
  12758. return new ggml_backend_event {
  12759. /* .device = */ dev,
  12760. /* .context = */ vkev,
  12761. };
  12762. }
  12763. static void ggml_backend_vk_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  12764. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12765. auto device = ggml_vk_get_device(ctx->device);
  12766. vk_event *vkev = (vk_event *)event->context;
  12767. device->device.destroyFence(vkev->fence);
  12768. device->device.destroyEvent(vkev->event);
  12769. delete vkev;
  12770. delete event;
  12771. }
  12772. static void ggml_backend_vk_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  12773. VK_LOG_DEBUG("ggml_backend_vk_device_event_synchronize(backend=" << dev << ", event=" << event << ")");
  12774. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12775. auto device = ggml_vk_get_device(ctx->device);
  12776. vk_event *vkev = (vk_event *)event->context;
  12777. VK_CHECK(device->device.waitForFences({ vkev->fence }, true, UINT64_MAX), "event_synchronize");
  12778. }
  12779. static vk_buffer ggml_vk_buffer_from_host_ptr(vk_device & device, void * ptr, size_t size) {
  12780. if (!device->external_memory_host) {
  12781. return {};
  12782. }
  12783. uintptr_t uptr = reinterpret_cast<uintptr_t>(ptr);
  12784. if (uptr & (device->min_imported_host_pointer_alignment - 1)) {
  12785. return {};
  12786. }
  12787. if (size & (device->min_imported_host_pointer_alignment - 1)) {
  12788. return {};
  12789. }
  12790. const vk::MemoryPropertyFlags property_flags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached;
  12791. vk_buffer buf {};
  12792. try {
  12793. buf = ggml_vk_create_buffer(device, size, { property_flags }, ptr);
  12794. } catch (vk::SystemError& e) {
  12795. GGML_LOG_WARN("ggml_vulkan: Failed ggml_vk_create_buffer (%s)\n", e.what());
  12796. }
  12797. return buf;
  12798. }
  12799. static ggml_backend_buffer_t ggml_backend_vk_device_buffer_from_host_ptr(ggml_backend_dev_t dev, void * ptr, size_t size, size_t max_tensor_size) {
  12800. VK_LOG_DEBUG("ggml_backend_vk_device_buffer_from_host_ptr(backend=" << dev << ", ptr=" << ptr << ", size=" << size << ")");
  12801. GGML_UNUSED(max_tensor_size);
  12802. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12803. auto device = ggml_vk_get_device(ctx->device);
  12804. vk_buffer buf = ggml_vk_buffer_from_host_ptr(device, ptr, size);
  12805. if (!buf) {
  12806. return {};
  12807. }
  12808. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(device, std::move(buf), device->name);
  12809. ggml_backend_buffer_t ret = ggml_backend_buffer_init(ggml_backend_vk_device_get_buffer_type(dev), ggml_backend_vk_buffer_interface, bufctx, size);
  12810. return ret;
  12811. }
  12812. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  12813. /* .get_name = */ ggml_backend_vk_device_get_name,
  12814. /* .get_description = */ ggml_backend_vk_device_get_description,
  12815. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  12816. /* .get_type = */ ggml_backend_vk_device_get_type,
  12817. /* .get_props = */ ggml_backend_vk_device_get_props,
  12818. /* .init_backend = */ ggml_backend_vk_device_init,
  12819. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  12820. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  12821. /* .buffer_from_host_ptr = */ ggml_backend_vk_device_buffer_from_host_ptr,
  12822. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  12823. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  12824. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  12825. /* .event_new = */ ggml_backend_vk_device_event_new,
  12826. /* .event_free = */ ggml_backend_vk_device_event_free,
  12827. /* .event_synchronize = */ ggml_backend_vk_device_event_synchronize,
  12828. };
  12829. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  12830. UNUSED(reg);
  12831. return GGML_VK_NAME;
  12832. }
  12833. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  12834. UNUSED(reg);
  12835. return ggml_backend_vk_get_device_count();
  12836. }
  12837. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  12838. static std::vector<ggml_backend_dev_t> devices;
  12839. static bool initialized = false;
  12840. {
  12841. static std::mutex mutex;
  12842. std::lock_guard<std::mutex> lock(mutex);
  12843. if (!initialized) {
  12844. const int min_batch_size = getenv("GGML_OP_OFFLOAD_MIN_BATCH") ? atoi(getenv("GGML_OP_OFFLOAD_MIN_BATCH")) : 32;
  12845. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  12846. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  12847. char desc[256];
  12848. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  12849. ctx->device = i;
  12850. ctx->name = GGML_VK_NAME + std::to_string(i);
  12851. ctx->description = desc;
  12852. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  12853. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  12854. ctx->op_offload_min_batch_size = min_batch_size;
  12855. devices.push_back(new ggml_backend_device {
  12856. /* .iface = */ ggml_backend_vk_device_i,
  12857. /* .reg = */ reg,
  12858. /* .context = */ ctx,
  12859. });
  12860. }
  12861. initialized = true;
  12862. }
  12863. }
  12864. GGML_ASSERT(device < devices.size());
  12865. return devices[device];
  12866. }
  12867. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  12868. /* .get_name = */ ggml_backend_vk_reg_get_name,
  12869. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  12870. /* .get_device = */ ggml_backend_vk_reg_get_device,
  12871. /* .get_proc_address = */ NULL,
  12872. };
  12873. ggml_backend_reg_t ggml_backend_vk_reg() {
  12874. static ggml_backend_reg reg = {
  12875. /* .api_version = */ GGML_BACKEND_API_VERSION,
  12876. /* .iface = */ ggml_backend_vk_reg_i,
  12877. /* .context = */ nullptr,
  12878. };
  12879. try {
  12880. ggml_vk_instance_init();
  12881. return &reg;
  12882. } catch (const vk::SystemError& e) {
  12883. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  12884. return nullptr;
  12885. } catch (const std::exception &e) {
  12886. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  12887. return nullptr;
  12888. } catch (...) {
  12889. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  12890. return nullptr;
  12891. }
  12892. }
  12893. // Extension availability
  12894. static bool ggml_vk_instance_layer_settings_available() {
  12895. #ifdef GGML_VULKAN_VALIDATE
  12896. // Check if validation layer provides the extension
  12897. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  12898. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  12899. if (layer_name == layer.layerName.data()) {
  12900. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  12901. if (strcmp("VK_EXT_layer_settings", ext.extensionName.data()) == 0) {
  12902. return true;
  12903. }
  12904. }
  12905. }
  12906. }
  12907. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_layer_settings not found." << std::endl;
  12908. #endif
  12909. return false;
  12910. }
  12911. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  12912. #ifdef __APPLE__
  12913. // Check for portability enumeration extension for MoltenVK support
  12914. for (const auto& properties : instance_extensions) {
  12915. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  12916. return true;
  12917. }
  12918. }
  12919. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  12920. #endif
  12921. return false;
  12922. UNUSED(instance_extensions);
  12923. }
  12924. // Extension availability
  12925. static bool ggml_vk_instance_debug_utils_ext_available(
  12926. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  12927. // Check for portability enumeration extension for MoltenVK support
  12928. for (const auto & properties : instance_extensions) {
  12929. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  12930. return true;
  12931. }
  12932. }
  12933. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  12934. return false;
  12935. UNUSED(instance_extensions);
  12936. }
  12937. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  12938. VkPhysicalDeviceFeatures2 device_features2;
  12939. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  12940. VkPhysicalDeviceVulkan11Features vk11_features;
  12941. vk11_features.pNext = nullptr;
  12942. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  12943. device_features2.pNext = &vk11_features;
  12944. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  12945. return vk11_features.storageBuffer16BitAccess;
  12946. }
  12947. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  12948. switch (props.vendorID) {
  12949. case VK_VENDOR_ID_INTEL:
  12950. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  12951. // while some older hardware (ex. Arc A770) has performance regressions
  12952. return arch == vk_device_architecture::INTEL_XE2;
  12953. case VK_VENDOR_ID_AMD:
  12954. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  12955. // Workaround for AMD proprietary driver reporting support on all GPUs
  12956. return arch == vk_device_architecture::AMD_RDNA3;
  12957. }
  12958. return true;
  12959. default:
  12960. return true;
  12961. }
  12962. }
  12963. // checks
  12964. #ifdef GGML_VULKAN_CHECK_RESULTS
  12965. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  12966. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  12967. return;
  12968. }
  12969. for (int j = 0; j < level; j++) {
  12970. std::cerr << " ";
  12971. }
  12972. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  12973. done.push_back(tensor);
  12974. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12975. if (tensor->src[i] != nullptr) {
  12976. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  12977. }
  12978. }
  12979. }
  12980. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  12981. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  12982. return;
  12983. }
  12984. i0 = std::max(i0, 5);
  12985. i1 = std::max(i1, 5);
  12986. i2 = std::max(i2, 0);
  12987. i3 = std::max(i3, 0);
  12988. fprintf(stderr, " ");
  12989. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12990. fprintf(stderr, "%7d ", idx1);
  12991. }
  12992. fprintf(stderr, "\n");
  12993. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12994. fprintf(stderr, "%7d: ", idx0);
  12995. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12996. 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]) {
  12997. float val;
  12998. if (tensor->type == GGML_TYPE_F32) {
  12999. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  13000. } else if (tensor->type == GGML_TYPE_F16) {
  13001. 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]));
  13002. } else if (tensor->type == GGML_TYPE_I32) {
  13003. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  13004. } else {
  13005. GGML_ABORT("fatal error");
  13006. }
  13007. fprintf(stderr, "% 7.2f ", val);
  13008. } else {
  13009. fprintf(stderr, " ");
  13010. }
  13011. }
  13012. fprintf(stderr, "\n");
  13013. }
  13014. }
  13015. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  13016. void * tensor_data = tensor->data;
  13017. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  13018. if (is_gpu) {
  13019. const size_t tensor_size = ggml_nbytes(tensor);
  13020. tensor_data = malloc(tensor_size);
  13021. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  13022. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  13023. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  13024. }
  13025. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  13026. 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;
  13027. if (tensor->src[0] != nullptr) {
  13028. 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;
  13029. }
  13030. if (tensor->src[1] != nullptr) {
  13031. 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;
  13032. }
  13033. std::cerr << std::endl << "Result:" << std::endl;
  13034. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13035. std::cerr << std::endl;
  13036. std::vector<const ggml_tensor *> done;
  13037. ggml_vk_print_graph_origin(tensor, done);
  13038. if (is_gpu) {
  13039. free(tensor_data);
  13040. }
  13041. }
  13042. void * comp_result;
  13043. size_t comp_size;
  13044. size_t comp_nb[GGML_MAX_DIMS];
  13045. size_t check_counter = 0;
  13046. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  13047. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  13048. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  13049. return;
  13050. }
  13051. check_counter++;
  13052. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  13053. return;
  13054. }
  13055. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  13056. struct ggml_init_params iparams = {
  13057. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  13058. /*.mem_buffer =*/ NULL,
  13059. /*.no_alloc =*/ false,
  13060. };
  13061. struct ggml_context * ggml_ctx = ggml_init(iparams);
  13062. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  13063. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  13064. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  13065. std::vector<void *> cloned_mallocs;
  13066. struct ggml_tensor * tensor_clone = nullptr;
  13067. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  13068. tensor = cgraph->nodes[tensor_idx + f];
  13069. for (int i = 0; i < GGML_MAX_SRC; i++) {
  13070. ggml_tensor * srci = tensor->src[i];
  13071. if (srci == nullptr) {
  13072. continue;
  13073. }
  13074. // If a src tensor has been cloned, use that one
  13075. auto it = cloned_tensors.find(srci);
  13076. if (it != cloned_tensors.end()) {
  13077. src_clone[i] = it->second;
  13078. continue;
  13079. }
  13080. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  13081. size_t srci_size = ggml_nbytes(srci);
  13082. src_clone[i] = srci_clone;
  13083. void *src_buffer = malloc(srci_size);
  13084. cloned_mallocs.push_back(src_buffer);
  13085. srci_clone->data = src_buffer;
  13086. if (ggml_backend_buffer_is_host(srci->buffer)) {
  13087. memcpy(srci_clone->data, srci->data, srci_size);
  13088. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13089. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  13090. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  13091. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  13092. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  13093. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  13094. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  13095. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  13096. const int idx = i3*srci->ne[2] + i2;
  13097. ggml_vk_buffer_read(buffer_gpu, offset + idx * srci->nb[2], ((char *)srci_clone->data + idx * srci_clone->nb[2]), srci->ne[1] * srci->nb[1]);
  13098. }
  13099. }
  13100. srci_clone->nb[0] = srci->nb[0];
  13101. srci_clone->nb[1] = srci->nb[1];
  13102. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  13103. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  13104. }
  13105. } else {
  13106. if (offset + srci_size >= buffer_gpu->size) {
  13107. srci_size = buffer_gpu->size - offset;
  13108. }
  13109. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  13110. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13111. }
  13112. } else {
  13113. GGML_ABORT("fatal error");
  13114. }
  13115. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13116. ggml_vk_print_tensor(srci, srci_name[i]);
  13117. }
  13118. }
  13119. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  13120. const float * params = (const float *)tensor->op_params;
  13121. tensor_clone = ggml_flash_attn_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3], params[0], params[1], params[2]);
  13122. if (src_clone[4]) {
  13123. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  13124. }
  13125. } else if (tensor->op == GGML_OP_MUL_MAT) {
  13126. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  13127. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  13128. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  13129. } else if (tensor->op == GGML_OP_SUB) {
  13130. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  13131. } else if (tensor->op == GGML_OP_MUL) {
  13132. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  13133. } else if (tensor->op == GGML_OP_DIV) {
  13134. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  13135. } else if (tensor->op == GGML_OP_CONCAT) {
  13136. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  13137. } else if (tensor->op == GGML_OP_UPSCALE) {
  13138. tensor_clone = ggml_interpolate(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], (ggml_scale_mode) tensor->op_params[0]);
  13139. } else if (tensor->op == GGML_OP_SCALE) {
  13140. const float * params = (const float *)tensor->op_params;
  13141. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  13142. } else if (tensor->op == GGML_OP_ADD1) {
  13143. tensor_clone = ggml_add1(ggml_ctx, src_clone[0], src_clone[1]);
  13144. } else if (tensor->op == GGML_OP_ARANGE) {
  13145. const float start = ggml_get_op_params_f32(tensor, 0);
  13146. const float stop = ggml_get_op_params_f32(tensor, 1);
  13147. const float step = ggml_get_op_params_f32(tensor, 2);
  13148. tensor_clone = ggml_arange(ggml_ctx, start, stop, step);
  13149. } else if (tensor->op == GGML_OP_FILL) {
  13150. const float value = ggml_get_op_params_f32(tensor, 0);
  13151. tensor_clone = ggml_fill(ggml_ctx, tensor_clone, value);
  13152. } else if (tensor->op == GGML_OP_SQR) {
  13153. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  13154. } else if (tensor->op == GGML_OP_SQRT) {
  13155. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  13156. } else if (tensor->op == GGML_OP_SIN) {
  13157. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  13158. } else if (tensor->op == GGML_OP_COS) {
  13159. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  13160. } else if (tensor->op == GGML_OP_LOG) {
  13161. tensor_clone = ggml_log(ggml_ctx, src_clone[0]);
  13162. } else if (tensor->op == GGML_OP_TRI) {
  13163. tensor_clone = ggml_tri(ggml_ctx, src_clone[0], (ggml_tri_type)ggml_get_op_params_i32(tensor, 0));
  13164. } else if (tensor->op == GGML_OP_DIAG) {
  13165. tensor_clone = ggml_diag(ggml_ctx, src_clone[0]);
  13166. } else if (tensor->op == GGML_OP_CLAMP) {
  13167. const float * params = (const float *)tensor->op_params;
  13168. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  13169. } else if (tensor->op == GGML_OP_PAD) {
  13170. tensor_clone = ggml_pad_ext(ggml_ctx, src_clone[0], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3],
  13171. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  13172. } else if (tensor->op == GGML_OP_REPEAT) {
  13173. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  13174. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  13175. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  13176. } else if (tensor->op == GGML_OP_ADD) {
  13177. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  13178. } else if (tensor->op == GGML_OP_ACC) {
  13179. tensor_clone = ggml_acc(ggml_ctx, src_clone[0], src_clone[1], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3]);
  13180. } else if (tensor->op == GGML_OP_NORM) {
  13181. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  13182. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  13183. const float * float_params = (const float *)tensor->op_params;
  13184. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  13185. } else if (tensor->op == GGML_OP_RMS_NORM) {
  13186. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  13187. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  13188. const float eps = ((float *) tensor->op_params)[0];
  13189. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  13190. } else if (tensor->op == GGML_OP_SILU_BACK) {
  13191. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  13192. } else if (tensor->op == GGML_OP_L2_NORM) {
  13193. const float eps = ((float *) tensor->op_params)[0];
  13194. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  13195. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  13196. if (tensor->src[1] != nullptr) {
  13197. const float * params = (const float *)tensor->op_params;
  13198. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  13199. } else {
  13200. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  13201. }
  13202. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  13203. tensor_clone = ggml_soft_max_ext_back(ggml_ctx, src_clone[0], src_clone[1], ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  13204. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  13205. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  13206. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  13207. const int n_dims = ((int32_t *) tensor->op_params)[1];
  13208. const int mode = ((int32_t *) tensor->op_params)[2];
  13209. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  13210. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  13211. const float freq_base = ((float *) tensor->op_params)[5];
  13212. const float freq_scale = ((float *) tensor->op_params)[6];
  13213. const float ext_factor = ((float *) tensor->op_params)[7];
  13214. const float attn_factor = ((float *) tensor->op_params)[8];
  13215. const float beta_fast = ((float *) tensor->op_params)[9];
  13216. const float beta_slow = ((float *) tensor->op_params)[10];
  13217. if (mode & GGML_ROPE_TYPE_MROPE) {
  13218. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  13219. if (tensor->op == GGML_OP_ROPE) {
  13220. tensor_clone = ggml_rope_multi(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, sections, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  13221. } else {
  13222. tensor_clone = ggml_rope_multi_back(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, sections, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  13223. }
  13224. } else {
  13225. if (tensor->op == GGML_OP_ROPE) {
  13226. tensor_clone = ggml_rope_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  13227. } else {
  13228. tensor_clone = ggml_rope_ext_back(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  13229. }
  13230. }
  13231. } else if (tensor->op == GGML_OP_UNARY) {
  13232. switch (ggml_get_unary_op(tensor)) {
  13233. case GGML_UNARY_OP_EXP:
  13234. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  13235. break;
  13236. case GGML_UNARY_OP_SILU:
  13237. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  13238. break;
  13239. case GGML_UNARY_OP_GELU:
  13240. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  13241. break;
  13242. case GGML_UNARY_OP_GELU_ERF:
  13243. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  13244. break;
  13245. case GGML_UNARY_OP_GELU_QUICK:
  13246. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  13247. break;
  13248. case GGML_UNARY_OP_RELU:
  13249. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  13250. break;
  13251. case GGML_UNARY_OP_XIELU:
  13252. tensor_clone = ggml_xielu(ggml_ctx, src_clone[0], 0, 0, 0, 0);
  13253. ggml_set_op_params_f32(tensor_clone, 1, ggml_get_op_params_f32(tensor, 1));
  13254. ggml_set_op_params_f32(tensor_clone, 2, ggml_get_op_params_f32(tensor, 2));
  13255. ggml_set_op_params_f32(tensor_clone, 3, ggml_get_op_params_f32(tensor, 3));
  13256. ggml_set_op_params_f32(tensor_clone, 4, ggml_get_op_params_f32(tensor, 4));
  13257. break;
  13258. case GGML_UNARY_OP_NEG:
  13259. tensor_clone = ggml_neg(ggml_ctx, src_clone[0]);
  13260. break;
  13261. case GGML_UNARY_OP_TANH:
  13262. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  13263. break;
  13264. case GGML_UNARY_OP_SIGMOID:
  13265. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  13266. break;
  13267. case GGML_UNARY_OP_HARDSIGMOID:
  13268. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  13269. break;
  13270. case GGML_UNARY_OP_HARDSWISH:
  13271. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  13272. break;
  13273. case GGML_UNARY_OP_ABS:
  13274. tensor_clone = ggml_abs(ggml_ctx, src_clone[0]);
  13275. break;
  13276. case GGML_UNARY_OP_SOFTPLUS:
  13277. tensor_clone = ggml_softplus(ggml_ctx, src_clone[0]);
  13278. break;
  13279. case GGML_UNARY_OP_STEP:
  13280. tensor_clone = ggml_step(ggml_ctx, src_clone[0]);
  13281. break;
  13282. case GGML_UNARY_OP_ROUND:
  13283. tensor_clone = ggml_round(ggml_ctx, src_clone[0]);
  13284. break;
  13285. case GGML_UNARY_OP_CEIL:
  13286. tensor_clone = ggml_ceil(ggml_ctx, src_clone[0]);
  13287. break;
  13288. case GGML_UNARY_OP_FLOOR:
  13289. tensor_clone = ggml_floor(ggml_ctx, src_clone[0]);
  13290. break;
  13291. case GGML_UNARY_OP_TRUNC:
  13292. tensor_clone = ggml_trunc(ggml_ctx, src_clone[0]);
  13293. break;
  13294. default:
  13295. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  13296. GGML_ABORT("fatal error");
  13297. }
  13298. } else if (tensor->op == GGML_OP_GLU) {
  13299. if (src_clone[1] == nullptr) {
  13300. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  13301. } else {
  13302. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  13303. }
  13304. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  13305. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  13306. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  13307. if (tensor->src[1] == nullptr) {
  13308. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  13309. tensor_clone->type = tensor->type;
  13310. } else {
  13311. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  13312. }
  13313. } else if (tensor->op == GGML_OP_CONT) {
  13314. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  13315. } else if (tensor->op == GGML_OP_RESHAPE) {
  13316. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  13317. } else if (tensor->op == GGML_OP_VIEW) {
  13318. tensor_clone = ggml_view_4d(ggml_ctx, src_clone[0], 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]);
  13319. } else if (tensor->op == GGML_OP_PERMUTE) {
  13320. int32_t * params = (int32_t *)tensor->op_params;
  13321. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  13322. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  13323. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  13324. } else if (tensor->op == GGML_OP_GET_ROWS) {
  13325. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  13326. } else if (tensor->op == GGML_OP_ARGSORT) {
  13327. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  13328. } else if (tensor->op == GGML_OP_TOP_K) {
  13329. tensor_clone = ggml_top_k(ggml_ctx, src_clone[0], tensor->ne[0]);
  13330. } else if (tensor->op == GGML_OP_SUM) {
  13331. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  13332. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  13333. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  13334. } else if (tensor->op == GGML_OP_CUMSUM) {
  13335. tensor_clone = ggml_cumsum(ggml_ctx, src_clone[0]);
  13336. } else if (tensor->op == GGML_OP_MEAN) {
  13337. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  13338. } else if (tensor->op == GGML_OP_ARGMAX) {
  13339. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  13340. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  13341. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  13342. } else if (tensor->op == GGML_OP_SOLVE_TRI) {
  13343. tensor_clone = ggml_solve_tri(ggml_ctx, src_clone[0], src_clone[1], true, true, false);
  13344. } else if (tensor->op == GGML_OP_IM2COL) {
  13345. const int32_t s0 = tensor->op_params[0];
  13346. const int32_t s1 = tensor->op_params[1];
  13347. const int32_t p0 = tensor->op_params[2];
  13348. const int32_t p1 = tensor->op_params[3];
  13349. const int32_t d0 = tensor->op_params[4];
  13350. const int32_t d1 = tensor->op_params[5];
  13351. const bool is_2D = tensor->op_params[6] == 1;
  13352. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  13353. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  13354. const int32_t s0 = tensor->op_params[0];
  13355. const int32_t s1 = tensor->op_params[1];
  13356. const int32_t s2 = tensor->op_params[2];
  13357. const int32_t p0 = tensor->op_params[3];
  13358. const int32_t p1 = tensor->op_params[4];
  13359. const int32_t p2 = tensor->op_params[5];
  13360. const int32_t d0 = tensor->op_params[6];
  13361. const int32_t d1 = tensor->op_params[7];
  13362. const int32_t d2 = tensor->op_params[8];
  13363. const int32_t IC = tensor->op_params[9];
  13364. tensor_clone = ggml_im2col_3d(ggml_ctx, src_clone[0], src_clone[1], IC, s0, s1, s2, p0, p1, p2, d0, d1, d2, tensor->type);
  13365. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  13366. const int32_t dim = tensor->op_params[0];
  13367. const int32_t max_period = tensor->op_params[1];
  13368. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  13369. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  13370. const int32_t s0 = tensor->op_params[0];
  13371. const int32_t p0 = tensor->op_params[1];
  13372. const int32_t d0 = tensor->op_params[2];
  13373. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  13374. } else if (tensor->op == GGML_OP_POOL_2D) {
  13375. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  13376. const int32_t k0 = tensor->op_params[1];
  13377. const int32_t k1 = tensor->op_params[2];
  13378. const int32_t s0 = tensor->op_params[3];
  13379. const int32_t s1 = tensor->op_params[4];
  13380. const int32_t p0 = tensor->op_params[5];
  13381. const int32_t p1 = tensor->op_params[6];
  13382. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  13383. } else if (tensor->op == GGML_OP_CONV_2D) {
  13384. const int32_t s0 = tensor->op_params[0];
  13385. const int32_t s1 = tensor->op_params[1];
  13386. const int32_t p0 = tensor->op_params[2];
  13387. const int32_t p1 = tensor->op_params[3];
  13388. const int32_t d0 = tensor->op_params[4];
  13389. const int32_t d1 = tensor->op_params[5];
  13390. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  13391. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  13392. const int32_t s0 = tensor->op_params[0];
  13393. const int32_t s1 = tensor->op_params[1];
  13394. const int32_t p0 = tensor->op_params[2];
  13395. const int32_t p1 = tensor->op_params[3];
  13396. const int32_t d0 = tensor->op_params[4];
  13397. const int32_t d1 = tensor->op_params[5];
  13398. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  13399. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  13400. const int32_t s = tensor->op_params[0];
  13401. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  13402. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  13403. const float * op_params = (const float *)tensor->op_params;
  13404. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  13405. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  13406. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  13407. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  13408. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  13409. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  13410. src_clone[4], src_clone[5], src_clone[6]);
  13411. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  13412. src_clone[0]->flags = tensor->src[0]->flags;
  13413. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  13414. src_clone[2], src_clone[3], src_clone[4]);
  13415. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  13416. src_clone[0]->flags = tensor->src[0]->flags;
  13417. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  13418. src_clone[2]);
  13419. } else if (tensor->op == GGML_OP_ADD_ID) {
  13420. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  13421. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  13422. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  13423. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  13424. } else if (tensor->op == GGML_OP_SSM_CONV) {
  13425. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  13426. } else if (tensor->op == GGML_OP_ROLL) {
  13427. const int32_t s0 = tensor->op_params[0];
  13428. const int32_t s1 = tensor->op_params[1];
  13429. const int32_t s2 = tensor->op_params[2];
  13430. const int32_t s3 = tensor->op_params[3];
  13431. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  13432. }
  13433. else {
  13434. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  13435. GGML_ABORT("fatal error");
  13436. }
  13437. cloned_tensors[tensor] = tensor_clone;
  13438. }
  13439. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  13440. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  13441. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  13442. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13443. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  13444. }
  13445. comp_size = ggml_nbytes(tensor_clone);
  13446. comp_result = malloc(comp_size);
  13447. memcpy(comp_result, tensor_clone->data, comp_size);
  13448. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13449. for (auto m : cloned_mallocs) {
  13450. free(m);
  13451. }
  13452. ggml_free(ggml_ctx);
  13453. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  13454. }
  13455. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  13456. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  13457. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  13458. return;
  13459. }
  13460. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  13461. return;
  13462. }
  13463. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  13464. ggml_tensor * src0 = tensor->src[0];
  13465. ggml_tensor * src1 = tensor->src[1];
  13466. ggml_tensor * src2 = tensor->src[2];
  13467. ggml_tensor * src3 = tensor->src[3];
  13468. void * tensor_data = tensor->data;
  13469. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13470. size_t tensor_size = ggml_nbytes(tensor);
  13471. tensor_data = malloc(tensor_size);
  13472. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  13473. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  13474. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  13475. if (offset + tensor_size >= buffer_gpu->size) {
  13476. tensor_size = buffer_gpu->size - offset;
  13477. }
  13478. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  13479. }
  13480. float first_error_result = -1.0f;
  13481. float first_error_correct = -1.0f;
  13482. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  13483. double avg_err = 0.0;
  13484. size_t counter = 0;
  13485. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  13486. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  13487. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  13488. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  13489. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  13490. float correct = 0.0f;
  13491. float result = 0.0f;
  13492. if (buffer_size_fit) {
  13493. if (tensor->type == GGML_TYPE_F32) {
  13494. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13495. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13496. } else if (tensor->type == GGML_TYPE_F16) {
  13497. 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]));
  13498. 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]));
  13499. } else if (tensor->type == GGML_TYPE_BF16) {
  13500. correct = ggml_bf16_to_fp32(*(ggml_bf16_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]));
  13501. result = ggml_bf16_to_fp32(*(ggml_bf16_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]));
  13502. } else if (tensor->type == GGML_TYPE_I32) {
  13503. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13504. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13505. } else if (tensor->type == GGML_TYPE_I64) {
  13506. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13507. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13508. } else {
  13509. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  13510. }
  13511. } else {
  13512. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  13513. GGML_ABORT("fatal error");
  13514. }
  13515. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  13516. 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;
  13517. 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;
  13518. if (src0 != nullptr) {
  13519. 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;
  13520. }
  13521. if (src1 != nullptr) {
  13522. 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;
  13523. }
  13524. if (src2 != nullptr) {
  13525. 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;
  13526. }
  13527. if (src3 != nullptr) {
  13528. 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;
  13529. }
  13530. 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;
  13531. std::cerr << std::endl << "Result:" << std::endl;
  13532. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  13533. std::cerr << std::endl << "Correct:" << std::endl;
  13534. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  13535. std::cerr << std::endl;
  13536. std::vector<const ggml_tensor *> done;
  13537. ggml_vk_print_graph_origin(tensor, done);
  13538. GGML_ABORT("fatal error");
  13539. }
  13540. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  13541. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  13542. first_error[0] = i0;
  13543. first_error[1] = i1;
  13544. first_error[2] = i2;
  13545. first_error[3] = i3;
  13546. first_error_result = result;
  13547. first_error_correct = correct;
  13548. }
  13549. // Special case, value is infinite, avoid NaN result in avg_err
  13550. // NaN also appears in results, if both are nan error is 0
  13551. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  13552. avg_err += std::fabs(correct - result) / denom;
  13553. }
  13554. counter++;
  13555. }
  13556. }
  13557. }
  13558. }
  13559. avg_err /= counter;
  13560. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13561. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13562. 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;
  13563. if (src0 != nullptr) {
  13564. 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;
  13565. }
  13566. if (src1 != nullptr) {
  13567. 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;
  13568. }
  13569. if (src2 != nullptr) {
  13570. 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;
  13571. }
  13572. if (src3 != nullptr) {
  13573. 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;
  13574. }
  13575. 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;
  13576. std::cerr << std::endl << "Result:" << std::endl;
  13577. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13578. std::cerr << std::endl << "Correct:" << std::endl;
  13579. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  13580. std::cerr << std::endl;
  13581. std::vector<const ggml_tensor *> done;
  13582. ggml_vk_print_graph_origin(tensor, done);
  13583. }
  13584. if (avg_err > 0.5 || std::isnan(avg_err)) {
  13585. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13586. 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;
  13587. if (src0 != nullptr) {
  13588. 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;
  13589. }
  13590. if (src1 != nullptr) {
  13591. 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;
  13592. }
  13593. if (src2 != nullptr) {
  13594. 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;
  13595. }
  13596. if (src3 != nullptr) {
  13597. 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;
  13598. }
  13599. 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;
  13600. std::cerr << std::endl << "Result:" << std::endl;
  13601. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  13602. std::cerr << std::endl << "Correct:" << std::endl;
  13603. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  13604. std::cerr << std::endl;
  13605. std::vector<const ggml_tensor *> done;
  13606. ggml_vk_print_graph_origin(tensor, done);
  13607. GGML_ABORT("fatal error");
  13608. } else {
  13609. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  13610. }
  13611. free(comp_result);
  13612. comp_result = nullptr;
  13613. comp_size = 0;
  13614. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13615. free(tensor_data);
  13616. }
  13617. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  13618. }
  13619. #endif
  13620. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)