ggml-vulkan.cpp 733 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814
  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 <unordered_map>
  33. #include <memory>
  34. #include <mutex>
  35. #include <future>
  36. #include <thread>
  37. #if defined(_MSC_VER)
  38. # define NOMINMAX 1
  39. # include <windows.h>
  40. # define YIELD() YieldProcessor()
  41. #elif defined(__clang__) || defined(__GNUC__)
  42. # if defined(__x86_64__) ||defined(__i386__)
  43. # include <immintrin.h>
  44. # define YIELD() _mm_pause()
  45. # elif defined(__arm__) || defined(__aarch64__)
  46. # if defined(__clang__)
  47. # include <arm_acle.h>
  48. # define YIELD() __yield()
  49. # else
  50. # define YIELD() asm volatile("yield")
  51. # endif
  52. # endif
  53. #endif
  54. #if !defined(YIELD)
  55. #define YIELD()
  56. #endif
  57. #include "ggml-impl.h"
  58. #include "ggml-backend-impl.h"
  59. #include "ggml-vulkan-shaders.hpp"
  60. // remove this once it's more widely available in the SDK
  61. #if !defined(VK_KHR_shader_bfloat16)
  62. #define VK_KHR_shader_bfloat16 1
  63. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  64. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  65. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  66. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  67. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  68. VkStructureType sType;
  69. void* pNext;
  70. VkBool32 shaderBFloat16Type;
  71. VkBool32 shaderBFloat16DotProduct;
  72. VkBool32 shaderBFloat16CooperativeMatrix;
  73. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  74. #endif
  75. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  76. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  77. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  78. #define VK_VENDOR_ID_AMD 0x1002
  79. #define VK_VENDOR_ID_APPLE 0x106b
  80. #define VK_VENDOR_ID_INTEL 0x8086
  81. #define VK_VENDOR_ID_NVIDIA 0x10de
  82. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  83. #define GGML_VK_MAX_NODES 8192
  84. #define VK_CHECK(err, msg) \
  85. do { \
  86. vk::Result err_ = (err); \
  87. if (err_ != vk::Result::eSuccess) { \
  88. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  89. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  90. exit(1); \
  91. } \
  92. } while (0)
  93. #ifdef GGML_VULKAN_DEBUG
  94. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  95. #else
  96. #define VK_LOG_DEBUG(msg) ((void) 0)
  97. #endif // GGML_VULKAN_DEBUG
  98. struct ggml_backend_vk_context;
  99. #define MAX_PARAMETER_COUNT 12
  100. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  101. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  102. struct vk_pipeline_struct {
  103. std::string name;
  104. vk::ShaderModule shader_module;
  105. vk::PipelineLayout layout;
  106. vk::Pipeline pipeline;
  107. uint32_t push_constant_size;
  108. uint32_t parameter_count;
  109. std::array<uint32_t, 3> wg_denoms;
  110. uint32_t align;
  111. // true if fields have been set by ggml_vk_create_pipeline
  112. bool initialized {};
  113. // set to true to request the pipeline is compiled after the dryrun
  114. bool needed {};
  115. // set to true when the shader has been compiled
  116. bool compiled {};
  117. // number of registers used, extracted from pipeline executable properties
  118. uint32_t register_count {};
  119. };
  120. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  121. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  122. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  123. struct vk_matmul_pipeline_struct {
  124. vk_pipeline l, m, s;
  125. vk_pipeline a_l, a_m, a_s;
  126. // Returns true when all unaligned pipelines are null.
  127. // We only check for unaligned variants since one of the unaligned pipelines must exist
  128. // while aligned pipelines are optional
  129. bool is_empty() const {
  130. return l == nullptr && m == nullptr && s == nullptr;
  131. }
  132. };
  133. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  134. struct vk_matmul_pipeline2 {
  135. vk_matmul_pipeline2() {
  136. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  137. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. }
  139. vk_matmul_pipeline f32acc;
  140. vk_matmul_pipeline f16acc;
  141. };
  142. struct vk_device_struct;
  143. typedef std::shared_ptr<vk_device_struct> vk_device;
  144. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  145. struct vk_buffer_struct;
  146. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  147. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  148. struct ggml_backend_vk_buffer_type_context {
  149. std::string name;
  150. vk_device device;
  151. };
  152. struct vk_queue;
  153. // Stores command pool/buffers. There's an instance of this
  154. // for each (context,queue) pair and for each (device,queue) pair.
  155. struct vk_command_pool {
  156. void init(vk_device& device, vk_queue *q_);
  157. void destroy(vk::Device& device);
  158. vk::CommandPool pool;
  159. uint32_t cmd_buffer_idx;
  160. std::vector<vk::CommandBuffer> cmd_buffers;
  161. vk_queue *q;
  162. };
  163. // Prevent simultaneous submissions to the same queue.
  164. // This could be per vk_queue if we stopped having two vk_queue structures
  165. // sharing the same vk::Queue.
  166. static std::mutex queue_mutex;
  167. struct vk_queue {
  168. uint32_t queue_family_index;
  169. vk::Queue queue;
  170. vk_command_pool cmd_pool;
  171. vk::PipelineStageFlags stage_flags;
  172. bool transfer_only;
  173. // copy everything except the cmd_pool
  174. void copyFrom(vk_queue &other) {
  175. queue_family_index = other.queue_family_index;
  176. queue = other.queue;
  177. stage_flags = other.stage_flags;
  178. transfer_only = other.transfer_only;
  179. }
  180. };
  181. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  182. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  183. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  184. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  186. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  187. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  188. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  189. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  190. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  191. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  192. /* .is_host = */ NULL,
  193. };
  194. #ifdef GGML_VULKAN_MEMORY_DEBUG
  195. class vk_memory_logger;
  196. #endif
  197. class vk_perf_logger;
  198. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  199. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  200. static constexpr uint32_t p021_max_gqa_ratio = 8;
  201. enum vk_device_architecture {
  202. OTHER,
  203. AMD_GCN,
  204. AMD_RDNA1,
  205. AMD_RDNA2,
  206. AMD_RDNA3,
  207. INTEL_XE2,
  208. NVIDIA_PRE_TURING,
  209. };
  210. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  211. vk::PhysicalDeviceProperties props = device.getProperties();
  212. if (props.vendorID == VK_VENDOR_ID_AMD) {
  213. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  214. bool amd_shader_core_properties = false;
  215. bool integer_dot_product = false;
  216. bool subgroup_size_control = false;
  217. for (const auto& properties : ext_props) {
  218. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  219. amd_shader_core_properties = true;
  220. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  221. integer_dot_product = true;
  222. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  223. subgroup_size_control = true;
  224. }
  225. }
  226. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  227. return vk_device_architecture::OTHER;
  228. }
  229. vk::PhysicalDeviceProperties2 props2;
  230. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  231. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  232. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  233. props2.pNext = &shader_core_props_amd;
  234. shader_core_props_amd.pNext = &integer_dot_props;
  235. integer_dot_props.pNext = &subgroup_size_control_props;
  236. device.getProperties2(&props2);
  237. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  238. return vk_device_architecture::AMD_GCN;
  239. }
  240. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  241. // RDNA
  242. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  243. return vk_device_architecture::AMD_RDNA1;
  244. }
  245. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  246. return vk_device_architecture::AMD_RDNA3;
  247. }
  248. return vk_device_architecture::AMD_RDNA2;
  249. }
  250. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  251. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  252. bool subgroup_size_control = false;
  253. for (const auto& properties : ext_props) {
  254. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  255. subgroup_size_control = true;
  256. }
  257. }
  258. if (!subgroup_size_control) {
  259. return vk_device_architecture::OTHER;
  260. }
  261. vk::PhysicalDeviceProperties2 props2;
  262. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  263. props2.pNext = &subgroup_size_control_props;
  264. device.getProperties2(&props2);
  265. if (subgroup_size_control_props.minSubgroupSize == 16) {
  266. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  267. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  268. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  269. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  270. return vk_device_architecture::INTEL_XE2;
  271. }
  272. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  273. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  274. bool cooperative_matrix = false;
  275. // Detect "pre-turing" based on lack of coopmat support.
  276. for (const auto& properties : ext_props) {
  277. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  278. cooperative_matrix = true;
  279. break;
  280. }
  281. }
  282. if (!cooperative_matrix) {
  283. return vk_device_architecture::NVIDIA_PRE_TURING;
  284. }
  285. }
  286. return vk_device_architecture::OTHER;
  287. }
  288. enum vk_conv_shapes {
  289. CONV_SHAPE_128x128,
  290. CONV_SHAPE_64x32,
  291. CONV_SHAPE_32x256,
  292. CONV_SHAPE_COUNT,
  293. };
  294. enum dmmv_wg_sizes {
  295. DMMV_WG_SIZE_SUBGROUP,
  296. DMMV_WG_SIZE_LARGE,
  297. DMMV_WG_SIZE_COUNT,
  298. };
  299. enum FaCodePath {
  300. FA_SCALAR,
  301. FA_COOPMAT1,
  302. FA_COOPMAT2,
  303. };
  304. struct vk_fa_pipeline_state {
  305. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  306. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  307. uint32_t HSK, HSV;
  308. bool small_rows;
  309. FaCodePath path;
  310. bool aligned;
  311. bool f32acc;
  312. bool operator<(const vk_fa_pipeline_state &b) const {
  313. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  314. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  315. }
  316. };
  317. enum shader_reduction_mode {
  318. SHADER_REDUCTION_MODE_SHMEM,
  319. SHADER_REDUCTION_MODE_HYBRID,
  320. SHADER_REDUCTION_MODE_SUBGROUP,
  321. SHADER_REDUCTION_MODE_COUNT,
  322. };
  323. static constexpr uint32_t num_argsort_pipelines = 11;
  324. static constexpr uint32_t max_argsort_cols = 1 << (num_argsort_pipelines-1);
  325. static constexpr uint32_t num_topk_moe_pipelines = 10;
  326. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  327. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  328. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  329. GGML_OP_RESHAPE };
  330. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  331. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  332. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  333. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  334. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  335. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  336. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  337. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  338. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  339. //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 ]
  340. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  341. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  342. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  343. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  344. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  345. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  346. { 1, 0, 0 }, // reshape->src[0] == softmax
  347. { 2, 0, 0 }, // argsort->src[0] == softmax
  348. { 3, 0, 2 }, // view->src[0] == argsort
  349. { 4, 0, 1 }, // get_rows->src[0] == reshape
  350. { 4, 1, 3 }, // get_rows->src[1] == view
  351. { 5, 0, 4 }, // reshape->src[0] == get_rows
  352. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  353. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  354. { 8, 0, 5 }, // div->src[0] == reshape
  355. { 8, 1, 7 }, // div->src[1] == clamp
  356. { 9, 0, 8 }, // reshape->src[0] == div
  357. };
  358. // same as early_softmax_norm but ending after the get_rows
  359. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  360. { 1, 0, 0 }, // reshape->src[0] == softmax
  361. { 2, 0, 0 }, // argsort->src[0] == softmax
  362. { 3, 0, 2 }, // view->src[0] == argsort
  363. { 4, 0, 1 }, // get_rows->src[0] == reshape
  364. { 4, 1, 3 }, // get_rows->src[1] == view
  365. };
  366. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  367. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  368. //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 ]
  369. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  370. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  371. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  372. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  373. { 1, 0, 0 }, // view->src[0] == argsort
  374. { 2, 1, 1 }, // get_rows->src[1] == view
  375. { 3, 0, 2 }, // reshape->src[0] == get_rows
  376. { 4, 0, 3 }, // soft_max->src[0] == reshape
  377. { 5, 0, 4 }, // reshape->src[0] == soft_max
  378. };
  379. enum topk_moe_mode {
  380. TOPK_MOE_EARLY_SOFTMAX,
  381. TOPK_MOE_EARLY_SOFTMAX_NORM,
  382. TOPK_MOE_LATE_SOFTMAX,
  383. TOPK_MOE_COUNT,
  384. };
  385. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  386. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  387. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  388. TOPK_MOE_LATE_SOFTMAX;
  389. return mode;
  390. }
  391. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  392. { 1, 0, 0 }, // view->src[0] == rope
  393. { 2, 0, 1 }, // set_rows->src[0] == view
  394. };
  395. struct vk_device_struct {
  396. std::recursive_mutex mutex;
  397. vk::PhysicalDevice physical_device;
  398. vk::PhysicalDeviceProperties properties;
  399. std::string name;
  400. uint64_t max_memory_allocation_size;
  401. uint64_t max_buffer_size;
  402. uint64_t suballocation_block_size;
  403. bool fp16;
  404. bool bf16;
  405. bool pipeline_robustness;
  406. vk::Device device;
  407. uint32_t vendor_id;
  408. vk::DriverId driver_id;
  409. vk_device_architecture architecture;
  410. vk_queue compute_queue;
  411. vk_queue transfer_queue;
  412. bool single_queue;
  413. uint32_t subgroup_size;
  414. uint32_t shader_core_count;
  415. bool uma;
  416. bool prefer_host_memory;
  417. bool float_controls_rte_fp16;
  418. bool subgroup_arithmetic;
  419. bool subgroup_shuffle;
  420. bool subgroup_ballot;
  421. bool subgroup_clustered;
  422. bool multi_add;
  423. bool shader_int64;
  424. bool buffer_device_address;
  425. bool add_rms_fusion;
  426. uint32_t partials_binding_alignment;
  427. bool integer_dot_product;
  428. // 0: default, 1: force mmvq, -1: disable mmvq
  429. int32_t mmvq_mode;
  430. bool subgroup_size_control;
  431. uint32_t subgroup_min_size;
  432. uint32_t subgroup_max_size;
  433. bool subgroup_require_full_support;
  434. bool coopmat_support;
  435. bool coopmat_acc_f32_support {};
  436. bool coopmat_acc_f16_support {};
  437. bool coopmat_bf16_support {};
  438. bool coopmat_support_16x16x16_f16acc {};
  439. bool coopmat_support_16x16x16_f32acc {};
  440. bool coopmat1_fa_support {};
  441. uint32_t coopmat_m;
  442. uint32_t coopmat_n;
  443. uint32_t coopmat_k;
  444. bool coopmat_int_support;
  445. uint32_t coopmat_int_m;
  446. uint32_t coopmat_int_n;
  447. uint32_t coopmat_int_k;
  448. bool coopmat2;
  449. bool pipeline_executable_properties_support {};
  450. size_t idx;
  451. bool mul_mat_l[GGML_TYPE_COUNT];
  452. bool mul_mat_m[GGML_TYPE_COUNT];
  453. bool mul_mat_s[GGML_TYPE_COUNT];
  454. bool mul_mat_id_l[GGML_TYPE_COUNT];
  455. bool mul_mat_id_m[GGML_TYPE_COUNT];
  456. bool mul_mat_id_s[GGML_TYPE_COUNT];
  457. // set to true to indicate that some shaders need to be compiled after the dryrun
  458. bool need_compiles {};
  459. vk::DescriptorSetLayout dsl;
  460. vk_matmul_pipeline pipeline_matmul_f32 {};
  461. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  462. vk_matmul_pipeline pipeline_matmul_bf16 {};
  463. vk_matmul_pipeline2 pipeline_matmul_f16;
  464. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  465. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  466. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  467. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  468. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  469. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  470. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  471. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  472. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  473. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  474. vk_pipeline pipeline_matmul_split_k_reduce;
  475. vk_pipeline pipeline_quantize_q8_1;
  476. vk_pipeline pipeline_quantize_q8_1_x4;
  477. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  478. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  479. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  480. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  481. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  482. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  483. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  484. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  485. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  486. vk_pipeline pipeline_acc_f32;
  487. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  488. vk_pipeline pipeline_add[2][2][2];
  489. vk_pipeline pipeline_add_norepeat[2][2][2];
  490. vk_pipeline pipeline_sub[2][2][2];
  491. vk_pipeline pipeline_sub_norepeat[2][2][2];
  492. vk_pipeline pipeline_mul[2][2][2];
  493. vk_pipeline pipeline_mul_norepeat[2][2][2];
  494. vk_pipeline pipeline_div[2][2][2];
  495. vk_pipeline pipeline_div_norepeat[2][2][2];
  496. vk_pipeline pipeline_add_rms[2][2][2];
  497. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  498. // indexed by num_additional_fused_ops == num_adds - 1
  499. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  500. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  501. vk_pipeline pipeline_add_id_f32;
  502. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  503. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32;
  504. vk_pipeline pipeline_scale_f32;
  505. vk_pipeline pipeline_sqr_f32;
  506. vk_pipeline pipeline_sqrt_f32;
  507. vk_pipeline pipeline_sin_f32;
  508. vk_pipeline pipeline_cos_f32;
  509. vk_pipeline pipeline_clamp_f32;
  510. vk_pipeline pipeline_pad_f32;
  511. vk_pipeline pipeline_roll_f32;
  512. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  513. 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;
  514. 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;
  515. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  516. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  517. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  518. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  519. vk_pipeline pipeline_norm_f32;
  520. vk_pipeline pipeline_group_norm_f32;
  521. vk_pipeline pipeline_rms_norm_f32;
  522. vk_pipeline pipeline_rms_norm_mul_f32;
  523. vk_pipeline pipeline_rms_norm_partials_f32;
  524. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  525. vk_pipeline pipeline_rms_norm_back_f32;
  526. vk_pipeline pipeline_l2_norm_f32;
  527. // [src/dst 0=fp32,1=fp16]
  528. vk_pipeline pipeline_exp[2];
  529. vk_pipeline pipeline_gelu[2];
  530. vk_pipeline pipeline_gelu_erf[2];
  531. vk_pipeline pipeline_gelu_quick[2];
  532. vk_pipeline pipeline_silu[2];
  533. vk_pipeline pipeline_relu[2];
  534. vk_pipeline pipeline_tanh[2];
  535. vk_pipeline pipeline_sigmoid[2];
  536. vk_pipeline pipeline_hardsigmoid[2];
  537. vk_pipeline pipeline_hardswish[2];
  538. vk_pipeline pipeline_geglu[2];
  539. vk_pipeline pipeline_reglu[2];
  540. vk_pipeline pipeline_swiglu[2];
  541. vk_pipeline pipeline_swiglu_oai[2];
  542. vk_pipeline pipeline_geglu_erf[2];
  543. vk_pipeline pipeline_geglu_quick[2];
  544. vk_pipeline pipeline_leaky_relu_f32;
  545. vk_pipeline pipeline_silu_back_f32;
  546. vk_pipeline pipeline_diag_mask_inf_f32;
  547. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  548. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  549. vk_pipeline pipeline_soft_max_back_f32;
  550. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  551. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  552. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  553. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  554. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  555. vk_pipeline pipeline_sum_rows_f32;
  556. vk_pipeline pipeline_argmax_f32;
  557. vk_pipeline pipeline_count_equal_i32;
  558. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  559. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  560. vk_pipeline pipeline_timestep_embedding_f32;
  561. vk_pipeline pipeline_conv_transpose_1d_f32;
  562. vk_pipeline pipeline_pool2d_f32;
  563. vk_pipeline pipeline_rwkv_wkv6_f32;
  564. vk_pipeline pipeline_rwkv_wkv7_f32;
  565. vk_pipeline pipeline_ssm_scan_f32_d128;
  566. vk_pipeline pipeline_ssm_scan_f32_d256;
  567. vk_pipeline pipeline_ssm_conv_f32;
  568. vk_pipeline pipeline_opt_step_adamw_f32;
  569. vk_pipeline pipeline_opt_step_sgd_f32;
  570. vk_pipeline pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  571. vk_pipeline pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  572. vk_pipeline pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  573. vk_pipeline pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  574. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  575. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  576. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  577. vk_pipeline pipeline_flash_attn_split_k_reduce;
  578. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT];
  579. std::vector<vk_pipeline_ref> all_pipelines;
  580. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  581. vk::Fence fence;
  582. vk_buffer sync_staging;
  583. ggml_backend_buffer_type buffer_type;
  584. bool disable_fusion;
  585. bool disable_host_visible_vidmem;
  586. bool allow_sysmem_fallback;
  587. bool disable_graph_optimize;
  588. #ifdef GGML_VULKAN_MEMORY_DEBUG
  589. std::unique_ptr<vk_memory_logger> memory_logger;
  590. #endif
  591. // for GGML_VK_PERF_LOGGER
  592. std::unique_ptr<vk_perf_logger> perf_logger;
  593. vk::QueryPool query_pool;
  594. int32_t num_queries;
  595. ~vk_device_struct() {
  596. VK_LOG_DEBUG("destroy device " << name);
  597. device.destroyFence(fence);
  598. ggml_vk_destroy_buffer(sync_staging);
  599. compute_queue.cmd_pool.destroy(device);
  600. transfer_queue.cmd_pool.destroy(device);
  601. for (auto& pipeline : all_pipelines) {
  602. if (pipeline.expired()) {
  603. continue;
  604. }
  605. vk_pipeline pl = pipeline.lock();
  606. ggml_vk_destroy_pipeline(device, pl);
  607. }
  608. all_pipelines.clear();
  609. device.destroyDescriptorSetLayout(dsl);
  610. device.destroy();
  611. }
  612. };
  613. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  614. cmd_buffer_idx = 0;
  615. q = q_;
  616. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  617. pool = device->device.createCommandPool(command_pool_create_info);
  618. }
  619. void vk_command_pool::destroy(vk::Device& device) {
  620. device.destroyCommandPool(pool);
  621. pool = nullptr;
  622. cmd_buffers.clear();
  623. }
  624. struct vk_buffer_struct {
  625. vk::Buffer buffer = VK_NULL_HANDLE;
  626. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  627. vk::MemoryPropertyFlags memory_property_flags;
  628. void * ptr;
  629. size_t size = 0;
  630. vk::DeviceAddress bda_addr {};
  631. vk_device device;
  632. ~vk_buffer_struct() {
  633. if (size == 0) {
  634. return;
  635. }
  636. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  637. device->device.freeMemory(device_memory);
  638. device->device.destroyBuffer(buffer);
  639. }
  640. };
  641. struct vk_subbuffer {
  642. vk_buffer buffer;
  643. uint64_t offset;
  644. uint64_t size;
  645. operator vk::DescriptorBufferInfo() const {
  646. return { buffer->buffer, offset, size };
  647. }
  648. };
  649. struct vk_semaphore {
  650. vk::Semaphore s;
  651. uint64_t value;
  652. };
  653. struct vk_submission {
  654. vk::CommandBuffer buffer;
  655. std::vector<vk_semaphore> wait_semaphores;
  656. std::vector<vk_semaphore> signal_semaphores;
  657. };
  658. typedef std::vector<vk_submission> vk_sequence;
  659. struct vk_mat_mat_push_constants {
  660. uint32_t M; uint32_t N; uint32_t K;
  661. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  662. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  663. uint32_t k_split;
  664. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  665. uint32_t padded_N;
  666. };
  667. struct vk_mat_vec_push_constants {
  668. uint32_t ncols;
  669. uint32_t stride_a;
  670. uint32_t stride_b;
  671. uint32_t stride_d;
  672. uint32_t batch_stride_a;
  673. uint32_t batch_stride_b;
  674. uint32_t batch_stride_d;
  675. uint32_t enable_bias;
  676. uint32_t ne02;
  677. uint32_t ne12;
  678. uint32_t broadcast2;
  679. uint32_t broadcast3;
  680. };
  681. struct vk_mat_mat_id_push_constants {
  682. uint32_t M; uint32_t N; uint32_t K;
  683. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  684. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  685. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  686. uint32_t padded_N;
  687. };
  688. struct vk_mat_vec_id_push_constants {
  689. uint32_t ncols;
  690. uint32_t stride_a;
  691. uint32_t stride_b;
  692. uint32_t stride_d;
  693. uint32_t batch_stride_a;
  694. uint32_t batch_stride_b;
  695. uint32_t batch_stride_d;
  696. uint32_t enable_bias;
  697. uint32_t nei0;
  698. uint32_t ne11;
  699. };
  700. struct vk_flash_attn_push_constants {
  701. uint32_t N;
  702. uint32_t KV;
  703. uint32_t ne1;
  704. uint32_t ne2;
  705. uint32_t ne3;
  706. uint32_t neq2;
  707. uint32_t neq3;
  708. uint32_t nek2;
  709. uint32_t nek3;
  710. uint32_t nev2;
  711. uint32_t nev3;
  712. uint32_t nem1;
  713. uint32_t nem2;
  714. uint32_t nem3;
  715. uint32_t nb01;
  716. uint32_t nb02;
  717. uint32_t nb03;
  718. uint32_t nb11;
  719. uint32_t nb12;
  720. uint32_t nb13;
  721. uint32_t nb21;
  722. uint32_t nb22;
  723. uint32_t nb23;
  724. float scale;
  725. float max_bias;
  726. float logit_softcap;
  727. uint32_t mask_n_head_log2;
  728. float m0;
  729. float m1;
  730. uint32_t gqa_ratio;
  731. uint32_t split_kv;
  732. uint32_t k_num;
  733. };
  734. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  735. struct vk_op_push_constants {
  736. uint32_t KX;
  737. uint32_t KY;
  738. float param1;
  739. float param2;
  740. };
  741. struct vk_op_glu_push_constants {
  742. uint32_t N;
  743. uint32_t ne00;
  744. uint32_t ne20;
  745. uint32_t mode; // 0: default, 1: swapped, 2: split
  746. float alpha; // for swiglu_oai
  747. float limit;
  748. };
  749. struct vk_op_unary_push_constants {
  750. uint32_t ne;
  751. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  752. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  753. uint32_t misalign_offsets;
  754. float param1; float param2;
  755. uint32_t ne0_012mp; uint32_t ne0_012L;
  756. uint32_t ne0_01mp; uint32_t ne0_01L;
  757. uint32_t ne0_0mp; uint32_t ne0_0L;
  758. uint32_t ne1_012mp; uint32_t ne1_012L;
  759. uint32_t ne1_01mp; uint32_t ne1_01L;
  760. uint32_t ne1_0mp; uint32_t ne1_0L;
  761. };
  762. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  763. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  764. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  765. ne = ne != 0 ? ne : ggml_nelements(dst);
  766. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  767. vk_op_unary_push_constants p{};
  768. p.ne = (uint32_t)ne;
  769. size_t src0_tsize = ggml_type_size(src0->type);
  770. p.ne00 = (uint32_t)src0->ne[0];
  771. p.ne01 = (uint32_t)src0->ne[1];
  772. p.ne02 = (uint32_t)src0->ne[2];
  773. p.ne03 = (uint32_t)src0->ne[3];
  774. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  775. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  776. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  777. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  778. size_t dst_tsize = ggml_type_size(dst->type);
  779. p.ne10 = (uint32_t)dst->ne[0];
  780. p.ne11 = (uint32_t)dst->ne[1];
  781. p.ne12 = (uint32_t)dst->ne[2];
  782. p.ne13 = (uint32_t)dst->ne[3];
  783. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  784. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  785. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  786. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  787. return p; // offsets are initialized later in ggml_vk_op
  788. }
  789. struct vk_op_pad_push_constants {
  790. uint32_t ne;
  791. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  792. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  793. uint32_t misalign_offsets;
  794. uint32_t lp0; uint32_t rp0;
  795. uint32_t lp1; uint32_t rp1;
  796. uint32_t lp2; uint32_t rp2;
  797. uint32_t lp3; uint32_t rp3;
  798. };
  799. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  800. int64_t ne = ggml_nelements(dst);
  801. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  802. vk_op_pad_push_constants p{};
  803. p.ne = (uint32_t)ne;
  804. size_t src0_tsize = ggml_type_size(src0->type);
  805. p.ne00 = (uint32_t)src0->ne[0];
  806. p.ne01 = (uint32_t)src0->ne[1];
  807. p.ne02 = (uint32_t)src0->ne[2];
  808. p.ne03 = (uint32_t)src0->ne[3];
  809. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  810. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  811. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  812. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  813. size_t dst_tsize = ggml_type_size(dst->type);
  814. p.ne10 = (uint32_t)dst->ne[0];
  815. p.ne11 = (uint32_t)dst->ne[1];
  816. p.ne12 = (uint32_t)dst->ne[2];
  817. p.ne13 = (uint32_t)dst->ne[3];
  818. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  819. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  820. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  821. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  822. p.lp0 = dst->op_params[0];
  823. p.rp0 = dst->op_params[1];
  824. p.lp1 = dst->op_params[2];
  825. p.rp1 = dst->op_params[3];
  826. p.lp2 = dst->op_params[4];
  827. p.rp2 = dst->op_params[5];
  828. p.lp3 = dst->op_params[6];
  829. p.rp3 = dst->op_params[7];
  830. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  831. }
  832. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  833. // Precompute mp (m' in the paper) and L such that division
  834. // can be computed using a multiply (high 32b of 64b result)
  835. // and a shift:
  836. //
  837. // n/d = (mulhi(n, mp) + n) >> L;
  838. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  839. {
  840. // compute L = ceil(log2(d));
  841. L = 0;
  842. while (L < 32 && (uint32_t{1} << L) < d) {
  843. L++;
  844. }
  845. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  846. }
  847. template <typename T> void init_pushconst_fastdiv(T &p) {
  848. GGML_UNUSED(p);
  849. static_assert(!std::is_const<T>::value, "unexpected type");
  850. }
  851. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  852. // Compute magic values to divide by these six numbers.
  853. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  854. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  855. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  856. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  857. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  858. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  859. }
  860. struct vk_op_binary_push_constants {
  861. uint32_t ne;
  862. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  863. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  864. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  865. uint32_t misalign_offsets;
  866. float param1; float param2; int32_t param3;
  867. };
  868. struct vk_op_multi_add_push_constants {
  869. // shape for dst
  870. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  871. // strides for srcs+dst
  872. uint32_t nb[MAX_PARAMETER_COUNT][4];
  873. uint32_t rms_partials;
  874. };
  875. // update multi_add.comp if this changes
  876. static_assert(MAX_PARAMETER_COUNT == 12);
  877. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  878. struct vk_op_topk_moe_push_constants {
  879. uint32_t n_rows;
  880. uint32_t n_expert_used;
  881. float clamp_min;
  882. float clamp_max;
  883. };
  884. struct vk_op_add_id_push_constants {
  885. uint32_t ne0;
  886. uint32_t ne1;
  887. uint32_t s01;
  888. uint32_t s02;
  889. uint32_t s11;
  890. uint32_t s21;
  891. };
  892. struct vk_op_diag_mask_push_constants {
  893. uint32_t ncols;
  894. uint32_t rows_per_channel;
  895. int32_t n_past;
  896. };
  897. struct vk_op_rope_push_constants {
  898. uint32_t ncols;
  899. uint32_t n_dims;
  900. float freq_scale;
  901. uint32_t p_delta_rows;
  902. float freq_base;
  903. float ext_factor;
  904. float attn_factor;
  905. float corr_dims[2];
  906. float theta_scale;
  907. uint32_t has_ff;
  908. uint32_t ne02;
  909. uint32_t s1;
  910. uint32_t s2;
  911. int32_t sections[4];
  912. uint32_t is_imrope;
  913. uint32_t is_back;
  914. uint32_t set_rows_stride;
  915. };
  916. struct vk_op_soft_max_push_constants {
  917. uint32_t KX;
  918. uint32_t KY;
  919. uint32_t ne00;
  920. uint32_t ne01;
  921. uint32_t ne02;
  922. uint32_t ne12;
  923. uint32_t ne13;
  924. uint32_t nb11;
  925. uint32_t nb12;
  926. uint32_t nb13;
  927. float scale;
  928. float max_bias;
  929. float m0;
  930. float m1;
  931. uint32_t n_head_log2;
  932. uint32_t nrows_x;
  933. uint32_t has_sinks;
  934. };
  935. struct vk_op_argsort_push_constants {
  936. uint32_t ncols;
  937. uint32_t nrows;
  938. int32_t order;
  939. };
  940. struct vk_op_im2col_push_constants {
  941. uint64_t dst_addr;
  942. uint32_t batch_offset; uint32_t offset_delta;
  943. uint32_t IC;
  944. uint32_t IW; uint32_t IH;
  945. uint32_t OW; uint32_t OH;
  946. uint32_t KW; uint32_t KH;
  947. uint32_t pelements;
  948. uint32_t CHW;
  949. int32_t s0; int32_t s1;
  950. int32_t p0; int32_t p1;
  951. int32_t d0; int32_t d1;
  952. };
  953. struct vk_op_im2col_3d_push_constants {
  954. uint64_t dst_addr;
  955. uint32_t nb10;
  956. uint32_t nb11;
  957. uint32_t nb12;
  958. uint32_t nb13;
  959. uint32_t s0;
  960. uint32_t s1;
  961. uint32_t s2;
  962. uint32_t p0;
  963. uint32_t p1;
  964. uint32_t p2;
  965. uint32_t d0;
  966. uint32_t d1;
  967. uint32_t d2;
  968. uint32_t IW;
  969. uint32_t IH;
  970. uint32_t ID;
  971. uint32_t IC;
  972. uint32_t KW;
  973. uint32_t OH;
  974. uint32_t KD_KH_KW;
  975. uint32_t KH_KW;
  976. uint32_t IC_KD_KH_KW;
  977. uint32_t N_OD_OH;
  978. uint32_t OD_OH;
  979. uint32_t OD_OH_OW_IC_KD_KH_KW;
  980. uint32_t OH_OW_IC_KD_KH_KW;
  981. uint32_t OW_IC_KD_KH_KW;
  982. uint32_t misalign_offsets;
  983. };
  984. struct vk_op_timestep_embedding_push_constants {
  985. uint32_t nb1;
  986. uint32_t dim;
  987. uint32_t max_period;
  988. };
  989. struct vk_op_conv_transpose_1d_push_constants {
  990. uint32_t Cout;
  991. uint32_t Cin;
  992. uint32_t K;
  993. uint32_t L;
  994. uint32_t KL;
  995. uint32_t nb01;
  996. uint32_t nb02;
  997. uint32_t nb11;
  998. uint32_t nb1;
  999. int32_t s0;
  1000. };
  1001. struct vk_op_pool2d_push_constants {
  1002. uint32_t IW; uint32_t IH;
  1003. uint32_t OW; uint32_t OH;
  1004. uint32_t OC;
  1005. uint32_t pelements;
  1006. uint32_t op;
  1007. int32_t k0; int32_t k1;
  1008. int32_t s0; int32_t s1;
  1009. int32_t p0; int32_t p1;
  1010. };
  1011. struct vk_op_rwkv_wkv6_push_constants {
  1012. uint32_t B;
  1013. uint32_t T;
  1014. uint32_t C;
  1015. uint32_t H;
  1016. };
  1017. struct vk_op_rwkv_wkv7_push_constants {
  1018. uint32_t B;
  1019. uint32_t T;
  1020. uint32_t C;
  1021. uint32_t H;
  1022. };
  1023. struct vk_op_ssm_scan_push_constants {
  1024. uint32_t nb02, nb03, nb12, nb13;
  1025. uint32_t nb21, nb22, nb31;
  1026. uint32_t nb42, nb43, nb52, nb53;
  1027. uint32_t s_off;
  1028. uint32_t n_head, d_head, n_group, n_tok;
  1029. };
  1030. struct vk_op_ssm_conv_push_constants {
  1031. uint32_t nb01, nb02;
  1032. uint32_t nb11;
  1033. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1034. uint32_t nc, ncs, nr, n_t, n_s;
  1035. };
  1036. struct vk_op_conv2d_push_constants {
  1037. uint32_t Cout;
  1038. uint32_t Cin;
  1039. uint32_t N;
  1040. uint32_t KW;
  1041. uint32_t KH;
  1042. uint32_t W;
  1043. uint32_t H;
  1044. uint32_t OW;
  1045. uint32_t OH;
  1046. uint32_t s0;
  1047. uint32_t s1;
  1048. uint32_t p0;
  1049. uint32_t p1;
  1050. uint32_t d0;
  1051. uint32_t d1;
  1052. uint32_t nb01;
  1053. uint32_t nb02;
  1054. uint32_t nb03;
  1055. uint32_t nb11;
  1056. uint32_t nb12;
  1057. uint32_t nb13;
  1058. uint32_t nb1;
  1059. uint32_t nb2;
  1060. uint32_t nb3;
  1061. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH
  1062. uint32_t KWmp; uint32_t KWL;
  1063. uint32_t KWKHmp; uint32_t KWKHL;
  1064. uint32_t OWmp; uint32_t OWL;
  1065. uint32_t OWOHmp; uint32_t OWOHL;
  1066. };
  1067. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1068. // Compute magic values to divide by KW, KW*KH, OW, OW*OH
  1069. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  1070. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  1071. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1072. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1073. }
  1074. struct vk_op_conv_transpose_2d_push_constants {
  1075. uint32_t Cout;
  1076. uint32_t Cin;
  1077. uint32_t N;
  1078. uint32_t KW;
  1079. uint32_t KH;
  1080. uint32_t W;
  1081. uint32_t H;
  1082. uint32_t OW;
  1083. uint32_t OH;
  1084. uint32_t s0;
  1085. uint32_t s1;
  1086. uint32_t p0;
  1087. uint32_t p1;
  1088. uint32_t d0;
  1089. uint32_t d1;
  1090. uint32_t nb01;
  1091. uint32_t nb02;
  1092. uint32_t nb03;
  1093. uint32_t nb11;
  1094. uint32_t nb12;
  1095. uint32_t nb13;
  1096. uint32_t nb1;
  1097. uint32_t nb2;
  1098. uint32_t nb3;
  1099. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH, s0, s1
  1100. uint32_t KWmp; uint32_t KWL;
  1101. uint32_t KWKHmp; uint32_t KWKHL;
  1102. uint32_t OWmp; uint32_t OWL;
  1103. uint32_t OWOHmp; uint32_t OWOHL;
  1104. uint32_t s0mp; uint32_t s0L;
  1105. uint32_t s1mp; uint32_t s1L;
  1106. };
  1107. template <> void init_pushconst_fastdiv(vk_op_conv_transpose_2d_push_constants &p) {
  1108. // Compute magic values to divide by KW, KW*KH, OW, OW*OH, s0, s1
  1109. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  1110. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  1111. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1112. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1113. init_fastdiv_values(p.s0, p.s0mp, p.s0L);
  1114. init_fastdiv_values(p.s1, p.s1mp, p.s1L);
  1115. }
  1116. struct vk_op_conv2d_dw_push_constants {
  1117. uint32_t ne;
  1118. uint32_t batches;
  1119. uint32_t channels;
  1120. uint32_t dst_w;
  1121. uint32_t dst_h;
  1122. uint32_t src_w;
  1123. uint32_t src_h;
  1124. uint32_t knl_w;
  1125. uint32_t knl_h;
  1126. int32_t stride_x;
  1127. int32_t stride_y;
  1128. int32_t pad_x;
  1129. int32_t pad_y;
  1130. int32_t dilation_x;
  1131. int32_t dilation_y;
  1132. };
  1133. struct vk_op_upscale_push_constants {
  1134. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1135. uint32_t ne00; uint32_t ne01;
  1136. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1137. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1138. float sf0; float sf1; float sf2; float sf3;
  1139. float pixel_offset;
  1140. };
  1141. struct vk_op_sum_rows_push_constants
  1142. {
  1143. uint32_t n_cols;
  1144. uint32_t ne01, ne02;
  1145. uint32_t nb01, nb02, nb03;
  1146. uint32_t nb11, nb12, nb13;
  1147. float weight;
  1148. uint32_t misalign_offsets;
  1149. uint32_t ne0_12mp, ne0_12L;
  1150. uint32_t ne0_1mp, ne0_1L;
  1151. };
  1152. 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) {
  1153. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1154. vk_op_sum_rows_push_constants p = {};
  1155. p.n_cols = (uint32_t)n_cols;
  1156. p.ne01 = (uint32_t)src->ne[1];
  1157. p.ne02 = (uint32_t)src->ne[2];
  1158. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1159. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1160. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1161. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1162. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1163. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1164. p.weight = 1.0f;
  1165. return p;
  1166. }
  1167. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1168. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1169. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1170. }
  1171. // Allow pre-recording command buffers
  1172. struct vk_staging_memcpy {
  1173. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1174. void * dst;
  1175. const void * src;
  1176. size_t n;
  1177. };
  1178. struct vk_staging_memset {
  1179. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1180. void * dst;
  1181. uint32_t val;
  1182. size_t n;
  1183. };
  1184. struct vk_context_struct {
  1185. vk_submission * s;
  1186. std::vector<vk_sequence> seqs;
  1187. int exit_tensor_idx;
  1188. std::vector<vk_staging_memcpy> in_memcpys;
  1189. std::vector<vk_staging_memcpy> out_memcpys;
  1190. std::vector<vk_staging_memset> memsets;
  1191. vk_command_pool * p {};
  1192. };
  1193. typedef std::shared_ptr<vk_context_struct> vk_context;
  1194. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1195. struct ggml_vk_garbage_collector {
  1196. std::vector<vk_semaphore> tl_semaphores;
  1197. std::vector<vk_semaphore> semaphores;
  1198. std::vector<vk::Event> events;
  1199. std::vector<vk_context> contexts;
  1200. };
  1201. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1202. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1203. static std::string format_size(size_t size) {
  1204. const size_t kib = 1024;
  1205. const size_t mib = kib * 1024;
  1206. const size_t gib = mib * 1024;
  1207. std::ostringstream oss;
  1208. oss << std::fixed << std::setprecision(2);
  1209. if (size >= gib) {
  1210. oss << static_cast<double>(size) / gib << " GiB";
  1211. } else if (size >= mib) {
  1212. oss << static_cast<double>(size) / mib << " MiB";
  1213. } else if (size >= kib) {
  1214. oss << static_cast<double>(size) / kib << " KiB";
  1215. } else {
  1216. oss << size << " B";
  1217. }
  1218. return oss.str();
  1219. }
  1220. class vk_memory_logger {
  1221. public:
  1222. vk_memory_logger(): total_device(0), total_host(0) {}
  1223. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1224. void log_deallocation(vk_buffer_ref buf_ref);
  1225. private:
  1226. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1227. size_t total_device;
  1228. size_t total_host;
  1229. };
  1230. #else
  1231. #define VK_LOG_MEMORY(msg) ((void) 0)
  1232. #endif // GGML_VULKAN_MEMORY_DEBUG
  1233. class vk_perf_logger {
  1234. public:
  1235. void print_timings() {
  1236. if (timings.empty()) {
  1237. return;
  1238. }
  1239. uint64_t total_all_op_times = 0;
  1240. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1241. for (const auto & t : timings) {
  1242. uint64_t total_op_times = 0;
  1243. for (const auto & time : t.second) {
  1244. total_op_times += time;
  1245. }
  1246. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1247. << " us";
  1248. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1249. auto it = flops.find(t.first);
  1250. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1251. uint64_t total_op_flops = 0;
  1252. for (const auto & elem : it->second) {
  1253. total_op_flops += elem;
  1254. }
  1255. std::cerr << " ("
  1256. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1257. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1258. << " GFLOPS/s)";
  1259. }
  1260. total_all_op_times += total_op_times;
  1261. std::cerr << std::endl;
  1262. }
  1263. if (timings.size() > 0) {
  1264. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1265. }
  1266. timings.clear();
  1267. flops.clear();
  1268. }
  1269. void log_timing(const ggml_tensor * node, uint64_t time) {
  1270. if (node->op == GGML_OP_UNARY) {
  1271. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1272. return;
  1273. }
  1274. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1275. const uint64_t m = node->src[0]->ne[1];
  1276. const uint64_t n = node->ne[1];
  1277. const uint64_t k = node->src[1]->ne[0];
  1278. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  1279. std::string name = ggml_op_name(node->op);
  1280. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1281. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1282. name += "_VEC";
  1283. }
  1284. name += " ";
  1285. name += ggml_type_name(node->src[0]->type);
  1286. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1287. if (batch > 1) {
  1288. name += " batch=" + std::to_string(batch);
  1289. }
  1290. timings[name].push_back(time);
  1291. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1292. return;
  1293. }
  1294. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1295. std::string name = ggml_op_name(node->op);
  1296. ggml_tensor * knl = node->src[0];
  1297. uint64_t OW = node->ne[0];
  1298. uint64_t OH = node->ne[1];
  1299. uint64_t N = node->ne[3];
  1300. uint64_t Cout = node->ne[2];
  1301. uint64_t KW = knl->ne[0];
  1302. uint64_t KH = knl->ne[1];
  1303. uint64_t Cin = node->src[1]->ne[2];
  1304. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1305. uint64_t size_M = Cout;
  1306. uint64_t size_K = Cin * KW * KH;
  1307. uint64_t size_N = N * OW * OH;
  1308. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1309. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1310. ", N=N*OW*OH=" + std::to_string(size_N);
  1311. flops[name].push_back(n_flops);
  1312. timings[name].push_back(time);
  1313. return;
  1314. }
  1315. if (node->op == GGML_OP_RMS_NORM) {
  1316. std::string name = ggml_op_name(node->op);
  1317. 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]) + ")";
  1318. timings[name].push_back(time);
  1319. return;
  1320. }
  1321. timings[ggml_op_name(node->op)].push_back(time);
  1322. }
  1323. private:
  1324. std::map<std::string, std::vector<uint64_t>> timings;
  1325. std::map<std::string, std::vector<uint64_t>> flops;
  1326. };
  1327. struct ggml_backend_vk_context {
  1328. std::string name;
  1329. vk_device device;
  1330. size_t semaphore_idx, event_idx;
  1331. ggml_vk_garbage_collector gc;
  1332. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1333. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials;
  1334. vk::Fence fence, almost_ready_fence;
  1335. bool almost_ready_fence_pending {};
  1336. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1337. // write partial sums to accumulate the square of the vector components
  1338. bool do_add_rms_partials;
  1339. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1340. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1341. const ggml_tensor * prealloc_y_last_tensor_used {};
  1342. // Track which nodes have been used since the last sync, and whether they were written to
  1343. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1344. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1345. // Track which prealloc buffers have pending reads that need to be synchronized.
  1346. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1347. // and set to true after the buffer contents are consumed.
  1348. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1349. vk_context_ref compute_ctx;
  1350. vk_context_ref transfer_ctx;
  1351. std::vector<vk_context_ref> tensor_ctxs;
  1352. std::vector<vk::DescriptorPool> descriptor_pools;
  1353. std::vector<vk::DescriptorSet> descriptor_sets;
  1354. uint32_t descriptor_set_idx {};
  1355. uint32_t pipeline_descriptor_set_requirements {};
  1356. vk_command_pool compute_cmd_pool;
  1357. vk_command_pool transfer_cmd_pool;
  1358. // number of additional consecutive nodes that are being fused with the
  1359. // node currently being processed
  1360. int num_additional_fused_ops {};
  1361. // Bitmask of which fused ops need to write an intermediate value to memory.
  1362. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1363. // If there's no fusion, bit 0 is still set.
  1364. int fused_ops_write_mask {};
  1365. };
  1366. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1367. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1368. if (tensor->view_src) {
  1369. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1370. }
  1371. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1372. }
  1373. struct ggml_backend_vk_buffer_context {
  1374. vk_device_ref device;
  1375. vk_buffer dev_buffer;
  1376. std::string name;
  1377. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1378. device(device),
  1379. dev_buffer(dev_buffer),
  1380. name(name) {
  1381. }
  1382. ~ggml_backend_vk_buffer_context() {
  1383. ggml_vk_destroy_buffer(dev_buffer);
  1384. }
  1385. };
  1386. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1387. static std::mutex log_mutex;
  1388. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1389. std::lock_guard<std::mutex> guard(log_mutex);
  1390. vk_buffer buf = buf_ref.lock();
  1391. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1392. const std::string type = device ? "device" : "host";
  1393. allocations[buf->buffer] = size;
  1394. total_device += device ? size : 0;
  1395. total_host += device ? 0 : size;
  1396. 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));
  1397. }
  1398. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1399. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1400. return;
  1401. }
  1402. std::lock_guard<std::mutex> guard(log_mutex);
  1403. vk_buffer buf = buf_ref.lock();
  1404. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1405. std::string type = device ? "device" : "host";
  1406. auto it = allocations.find(buf->buffer);
  1407. total_device -= device ? it->second : 0;
  1408. total_host -= device ? 0 : it->second;
  1409. if (it != allocations.end()) {
  1410. 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));
  1411. allocations.erase(it);
  1412. } else {
  1413. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1414. }
  1415. }
  1416. #endif // GGML_VULKAN_MEMORY_DEBUG
  1417. struct vk_instance_t {
  1418. vk::Instance instance;
  1419. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1420. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1421. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1422. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1423. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1424. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1425. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1426. std::vector<size_t> device_indices;
  1427. std::vector<bool> device_supports_membudget;
  1428. vk_device devices[GGML_VK_MAX_DEVICES];
  1429. };
  1430. static bool vk_instance_initialized = false;
  1431. static vk_instance_t vk_instance;
  1432. static bool vk_perf_logger_enabled = false;
  1433. #ifdef GGML_VULKAN_CHECK_RESULTS
  1434. static size_t vk_skip_checks;
  1435. static size_t vk_output_tensor;
  1436. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1437. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1438. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1439. #endif
  1440. 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);
  1441. static void ggml_backend_vk_free(ggml_backend_t backend);
  1442. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1443. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1444. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1445. return range;
  1446. }
  1447. // Wait for ctx->fence to be signaled.
  1448. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1449. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1450. // during this wait.
  1451. if (ctx->almost_ready_fence_pending) {
  1452. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1453. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1454. ctx->almost_ready_fence_pending = false;
  1455. }
  1456. // Spin (w/pause) waiting for the graph to finish executing.
  1457. vk::Result result;
  1458. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1459. if (result != vk::Result::eNotReady) {
  1460. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1461. exit(1);
  1462. }
  1463. for (uint32_t i = 0; i < 100; ++i) {
  1464. YIELD();
  1465. YIELD();
  1466. YIELD();
  1467. YIELD();
  1468. YIELD();
  1469. YIELD();
  1470. YIELD();
  1471. YIELD();
  1472. YIELD();
  1473. YIELD();
  1474. }
  1475. }
  1476. ctx->device->device.resetFences({ ctx->fence });
  1477. }
  1478. // variables to track number of compiles in progress
  1479. static uint32_t compile_count = 0;
  1480. static std::mutex compile_count_mutex;
  1481. static std::condition_variable compile_count_cond;
  1482. 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,
  1483. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1484. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1485. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1486. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1487. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1488. GGML_ASSERT(parameter_count > 0);
  1489. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1490. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1491. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1492. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1493. vk::PushConstantRange pcr(
  1494. vk::ShaderStageFlagBits::eCompute,
  1495. 0,
  1496. pipeline->push_constant_size
  1497. );
  1498. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1499. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1500. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1501. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1502. specialization_entries[i].constantID = i;
  1503. specialization_entries[i].offset = i * sizeof(uint32_t);
  1504. specialization_entries[i].size = sizeof(uint32_t);
  1505. }
  1506. vk::SpecializationInfo specialization_info(
  1507. specialization_entries.size(),
  1508. specialization_entries.data(),
  1509. specialization_constants.size() * sizeof(uint32_t),
  1510. specialization_constants.data()
  1511. );
  1512. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1513. if (device->subgroup_require_full_support && require_full_subgroups) {
  1514. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1515. }
  1516. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1517. pipeline_shader_stage_create_flags,
  1518. vk::ShaderStageFlagBits::eCompute,
  1519. pipeline->shader_module,
  1520. entrypoint.c_str(),
  1521. &specialization_info);
  1522. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1523. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1524. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1525. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1526. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1527. }
  1528. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1529. device->pipeline_executable_properties_support ?
  1530. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1531. vk::PipelineCreateFlags{},
  1532. pipeline_shader_create_info,
  1533. pipeline->layout);
  1534. vk::PipelineRobustnessCreateInfoEXT rci;
  1535. if (device->pipeline_robustness && disable_robustness) {
  1536. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1537. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1538. compute_pipeline_create_info.setPNext(&rci);
  1539. }
  1540. try {
  1541. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1542. } catch (const vk::SystemError& e) {
  1543. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1544. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1545. throw e;
  1546. }
  1547. pipeline->compiled = true;
  1548. if (vk_instance.debug_utils_support) {
  1549. vk::DebugUtilsObjectNameInfoEXT duoni;
  1550. duoni.objectType = vk::ObjectType::ePipeline;
  1551. duoni.pObjectName = pipeline->name.c_str();
  1552. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1553. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1554. }
  1555. if (device->pipeline_executable_properties_support) {
  1556. vk::PipelineExecutableInfoKHR executableInfo;
  1557. executableInfo.pipeline = pipeline->pipeline;
  1558. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1559. for (auto & s : statistics) {
  1560. // "Register Count" is reported by NVIDIA drivers.
  1561. if (strcmp(s.name, "Register Count") == 0) {
  1562. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1563. pipeline->register_count = (uint32_t)s.value.u64;
  1564. }
  1565. }
  1566. }
  1567. {
  1568. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1569. device->all_pipelines.push_back(pipeline);
  1570. }
  1571. {
  1572. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1573. assert(compile_count > 0);
  1574. compile_count--;
  1575. }
  1576. compile_count_cond.notify_all();
  1577. }
  1578. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1579. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1580. device.destroyPipelineLayout(pipeline->layout);
  1581. device.destroyShaderModule(pipeline->shader_module);
  1582. device.destroyPipeline(pipeline->pipeline);
  1583. }
  1584. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1585. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1586. ctx->pipeline_descriptor_set_requirements += n;
  1587. if (!pipeline->compiled) {
  1588. pipeline->needed = true;
  1589. ctx->device->need_compiles = true;
  1590. }
  1591. }
  1592. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1593. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1594. // Enough descriptors are available
  1595. return;
  1596. }
  1597. vk_device& device = ctx->device;
  1598. uint32_t to_alloc = ctx->pipeline_descriptor_set_requirements - ctx->descriptor_sets.size();
  1599. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1600. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1601. while (to_alloc > 0) {
  1602. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1603. to_alloc -= alloc_count;
  1604. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1605. if (pool_idx >= ctx->descriptor_pools.size()) {
  1606. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1607. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1608. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1609. }
  1610. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1611. for (uint32_t i = 0; i < alloc_count; i++) {
  1612. layouts[i] = device->dsl;
  1613. }
  1614. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1615. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1616. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1617. pool_idx++;
  1618. }
  1619. }
  1620. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1621. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1622. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1623. // Reuse command buffer
  1624. return p.cmd_buffers[p.cmd_buffer_idx++];
  1625. }
  1626. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1627. p.pool,
  1628. vk::CommandBufferLevel::ePrimary,
  1629. 1);
  1630. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1631. auto buf = cmd_buffers.front();
  1632. p.cmd_buffers.push_back(buf);
  1633. p.cmd_buffer_idx++;
  1634. return buf;
  1635. }
  1636. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1637. if (ctx->seqs.empty()) {
  1638. if (fence) {
  1639. std::lock_guard<std::mutex> guard(queue_mutex);
  1640. ctx->p->q->queue.submit({}, fence);
  1641. }
  1642. return;
  1643. }
  1644. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1645. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1646. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1647. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1648. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1649. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1650. std::vector<vk::SubmitInfo> submit_infos;
  1651. int idx = -1;
  1652. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1653. size_t reserve = 0;
  1654. for (const auto& sequence : ctx->seqs) {
  1655. reserve += sequence.size();
  1656. }
  1657. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1658. tl_wait_semaphores.reserve(reserve);
  1659. tl_wait_vals.reserve(reserve);
  1660. tl_signal_semaphores.reserve(reserve);
  1661. tl_signal_vals.reserve(reserve);
  1662. tl_submit_infos.reserve(reserve);
  1663. submit_infos.reserve(reserve);
  1664. stage_flags.reserve(reserve);
  1665. for (const auto& sequence : ctx->seqs) {
  1666. for (const auto& submission : sequence) {
  1667. stage_flags.push_back({});
  1668. idx++;
  1669. tl_wait_vals.push_back({});
  1670. tl_wait_semaphores.push_back({});
  1671. tl_signal_vals.push_back({});
  1672. tl_signal_semaphores.push_back({});
  1673. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1674. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1675. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1676. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1677. }
  1678. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1679. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1680. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1681. }
  1682. tl_submit_infos.push_back({
  1683. (uint32_t) submission.wait_semaphores.size(),
  1684. tl_wait_vals[idx].data(),
  1685. (uint32_t) submission.signal_semaphores.size(),
  1686. tl_signal_vals[idx].data(),
  1687. });
  1688. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1689. tl_submit_infos[idx].pNext = nullptr;
  1690. vk::SubmitInfo si{
  1691. (uint32_t) submission.wait_semaphores.size(),
  1692. tl_wait_semaphores[idx].data(),
  1693. stage_flags[idx].data(),
  1694. 1,
  1695. &submission.buffer,
  1696. (uint32_t) submission.signal_semaphores.size(),
  1697. tl_signal_semaphores[idx].data(),
  1698. };
  1699. si.setPNext(&tl_submit_infos[idx]);
  1700. submit_infos.push_back(si);
  1701. }
  1702. }
  1703. std::lock_guard<std::mutex> guard(queue_mutex);
  1704. ctx->p->q->queue.submit(submit_infos, fence);
  1705. ctx->seqs.clear();
  1706. }
  1707. 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) {
  1708. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1709. const uint32_t qfsize = queue_family_props.size();
  1710. // Try with avoid preferences first
  1711. for (uint32_t i = 0; i < qfsize; i++) {
  1712. 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)) {
  1713. return i;
  1714. }
  1715. }
  1716. // Fall back to only required
  1717. for (size_t i = 0; i < qfsize; i++) {
  1718. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1719. return i;
  1720. }
  1721. }
  1722. // Fall back to reusing compute queue
  1723. for (size_t i = 0; i < qfsize; i++) {
  1724. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1725. return i;
  1726. }
  1727. }
  1728. // Fall back to ignoring min_num_queries
  1729. for (size_t i = 0; i < qfsize; i++) {
  1730. if (queue_family_props[i].queueFlags & required) {
  1731. return i;
  1732. }
  1733. }
  1734. // 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.
  1735. // 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.
  1736. if (compute_index >= 0) {
  1737. return compute_index;
  1738. }
  1739. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1740. for(auto &q_family : queue_family_props) {
  1741. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1742. }
  1743. abort();
  1744. }
  1745. 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) {
  1746. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1747. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1748. q.queue_family_index = queue_family_index;
  1749. q.transfer_only = transfer_only;
  1750. q.cmd_pool.init(device, &q);
  1751. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1752. q.stage_flags = stage_flags;
  1753. }
  1754. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1755. vk_context result = std::make_shared<vk_context_struct>();
  1756. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1757. ctx->gc.contexts.emplace_back(result);
  1758. result->p = &p;
  1759. return result;
  1760. }
  1761. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1762. vk_context result = std::make_shared<vk_context_struct>();
  1763. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1764. result->p = &p;
  1765. return result;
  1766. }
  1767. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1768. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1769. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1770. vk::SemaphoreCreateInfo ci{};
  1771. ci.setPNext(&tci);
  1772. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1773. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1774. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1775. }
  1776. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1777. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1778. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1779. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1780. vk::SemaphoreCreateInfo ci{};
  1781. ci.setPNext(&tci);
  1782. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1783. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1784. }
  1785. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1786. }
  1787. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1788. if (ctx->event_idx >= ctx->gc.events.size()) {
  1789. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1790. }
  1791. return ctx->gc.events[ctx->event_idx++];
  1792. }
  1793. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1794. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1795. // Requires command buffers to be done
  1796. device->device.resetCommandPool(p.pool);
  1797. p.cmd_buffer_idx = 0;
  1798. }
  1799. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1800. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1801. // Arbitrary frequency to cleanup/reuse command buffers
  1802. static constexpr uint32_t cleanup_frequency = 10;
  1803. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1804. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1805. }
  1806. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1807. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1808. }
  1809. }
  1810. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1811. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1812. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1813. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1814. (flags & memory_type.propertyFlags) == flags &&
  1815. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1816. return static_cast<int32_t>(i);
  1817. }
  1818. }
  1819. return UINT32_MAX;
  1820. }
  1821. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1822. 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]) << ")");
  1823. if (size > device->max_buffer_size) {
  1824. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  1825. }
  1826. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1827. if (size == 0) {
  1828. buf->size = 0;
  1829. return buf;
  1830. }
  1831. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1832. vk::MemoryAllocateFlags mem_flags {};
  1833. if (device->buffer_device_address) {
  1834. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1835. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1836. }
  1837. vk::BufferCreateInfo buffer_create_info{
  1838. vk::BufferCreateFlags(),
  1839. size,
  1840. usage_flags,
  1841. vk::SharingMode::eExclusive,
  1842. 0,
  1843. nullptr,
  1844. };
  1845. buf->buffer = device->device.createBuffer(buffer_create_info);
  1846. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1847. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1848. const vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  1849. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  1850. const auto & req_flags = *it;
  1851. uint32_t memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  1852. if (memory_type_index == UINT32_MAX) {
  1853. continue;
  1854. }
  1855. buf->memory_property_flags = req_flags;
  1856. try {
  1857. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index, &mem_flags_info });
  1858. break;
  1859. } catch (const vk::SystemError& e) {
  1860. // loop and retry
  1861. // during last attempt throw the exception
  1862. if (it + 1 == req_flags_list.end()) {
  1863. device->device.destroyBuffer(buf->buffer);
  1864. throw e;
  1865. }
  1866. }
  1867. }
  1868. if (!buf->device_memory) {
  1869. device->device.destroyBuffer(buf->buffer);
  1870. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1871. }
  1872. buf->ptr = nullptr;
  1873. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1874. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1875. }
  1876. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1877. buf->device = device;
  1878. buf->size = size;
  1879. if (device->buffer_device_address) {
  1880. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  1881. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  1882. }
  1883. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1884. device->memory_logger->log_allocation(buf, size);
  1885. #endif
  1886. return buf;
  1887. }
  1888. 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)) {
  1889. try {
  1890. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  1891. } catch (const vk::SystemError& e) {
  1892. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1893. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1894. throw e;
  1895. }
  1896. }
  1897. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1898. vk_buffer buf;
  1899. try {
  1900. if (device->prefer_host_memory) {
  1901. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1902. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1903. } else if (device->uma) {
  1904. // Fall back to host memory type
  1905. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1906. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1907. } else if (device->disable_host_visible_vidmem) {
  1908. if (device->allow_sysmem_fallback) {
  1909. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1910. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1911. } else {
  1912. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  1913. }
  1914. } else {
  1915. // use rebar if available, otherwise fallback to device only visible memory
  1916. if (device->allow_sysmem_fallback) {
  1917. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1918. vk::MemoryPropertyFlagBits::eDeviceLocal,
  1919. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1920. } else {
  1921. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1922. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1923. }
  1924. }
  1925. } catch (const vk::SystemError& e) {
  1926. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1927. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1928. throw e;
  1929. }
  1930. return buf;
  1931. }
  1932. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1933. if (buf == nullptr) {
  1934. return;
  1935. }
  1936. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1937. if (buf->device != nullptr) {
  1938. buf->device->memory_logger->log_deallocation(buf);
  1939. }
  1940. #endif
  1941. buf.reset();
  1942. }
  1943. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  1944. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  1945. }
  1946. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  1947. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1948. const bool transfer_queue = subctx->p->q->transfer_only;
  1949. if (ctx) {
  1950. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  1951. }
  1952. subctx->s->buffer.pipelineBarrier(
  1953. subctx->p->q->stage_flags,
  1954. subctx->p->q->stage_flags,
  1955. {},
  1956. { {
  1957. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1958. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1959. } },
  1960. {},
  1961. {}
  1962. );
  1963. }
  1964. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1965. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1966. if (events.empty()) {
  1967. return;
  1968. }
  1969. ctx->s->buffer.waitEvents(
  1970. events,
  1971. ctx->p->q->stage_flags,
  1972. ctx->p->q->stage_flags,
  1973. {},
  1974. {},
  1975. {}
  1976. );
  1977. }
  1978. // number of rows/cols for flash attention shader
  1979. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1980. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  1981. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  1982. if (hsv >= 192) {
  1983. return 2;
  1984. } else {
  1985. return 8;
  1986. }
  1987. }
  1988. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  1989. // 128 threads split into four subgroups, each subgroup does 1/4
  1990. // of the Bc dimension.
  1991. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  1992. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  1993. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  1994. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  1995. if (path == FA_COOPMAT2) {
  1996. return flash_attention_num_small_rows;
  1997. } else {
  1998. return scalar_flash_attention_num_small_rows;
  1999. }
  2000. }
  2001. 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) {
  2002. GGML_UNUSED(clamp);
  2003. GGML_UNUSED(hsv);
  2004. if (path == FA_SCALAR) {
  2005. if (small_rows) {
  2006. return {scalar_flash_attention_num_small_rows, 64};
  2007. } else {
  2008. if ((hsv | hsk) & 8) {
  2009. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2010. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2011. return {get_fa_scalar_num_large_rows(hsv), 64};
  2012. } else {
  2013. return {get_fa_scalar_num_large_rows(hsv), 32};
  2014. }
  2015. }
  2016. }
  2017. if (path == FA_COOPMAT1) {
  2018. if (small_rows) {
  2019. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2020. } else {
  2021. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2022. }
  2023. }
  2024. // small rows, large cols
  2025. if (small_rows) {
  2026. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2027. }
  2028. // small cols to reduce register count
  2029. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2030. if (hsk >= 512 || hsv >= 512) {
  2031. return {32, 32};
  2032. } else {
  2033. return {64, 32};
  2034. }
  2035. }
  2036. return {64, 64};
  2037. }
  2038. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  2039. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  2040. }
  2041. 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) {
  2042. uint32_t lut_size = 0;
  2043. switch (src0_type) {
  2044. case GGML_TYPE_IQ1_S:
  2045. case GGML_TYPE_IQ1_M:
  2046. lut_size = 2*2048;
  2047. break;
  2048. case GGML_TYPE_IQ2_XXS:
  2049. lut_size = 8*256;
  2050. break;
  2051. case GGML_TYPE_IQ2_XS:
  2052. lut_size = 8*512;
  2053. break;
  2054. case GGML_TYPE_IQ2_S:
  2055. lut_size = 8*1024;
  2056. break;
  2057. case GGML_TYPE_IQ3_XXS:
  2058. lut_size = 4*256;
  2059. break;
  2060. case GGML_TYPE_IQ3_S:
  2061. lut_size = 4*512;
  2062. break;
  2063. case GGML_TYPE_IQ4_NL:
  2064. case GGML_TYPE_IQ4_XS:
  2065. case GGML_TYPE_MXFP4:
  2066. lut_size = 4*16;
  2067. break;
  2068. default:
  2069. break;
  2070. }
  2071. // Needs to be kept up to date on shader changes
  2072. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2073. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2074. const uint32_t warps = warptile[0] / warptile[10];
  2075. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2076. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2077. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2078. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2079. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2080. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2081. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2082. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2083. return supported;
  2084. }
  2085. struct GpuPipelineConfig {
  2086. // GPU architecture identifier.
  2087. // Example: vk_device_architecture::AMD_GCN
  2088. vk_device_architecture arch;
  2089. // Mapping of pipeline names to their specific subgroup sizes.
  2090. // Example: {"soft_max_f32", 64}
  2091. std::unordered_map<std::string, uint32_t> pipelines;
  2092. // Default subgroup size for this GPU.
  2093. // Defaults to 0 if not explicitly provided.
  2094. uint32_t default_subgroup_size = 0;
  2095. };
  2096. // Pipeline configuration for RDNA1 GPUs.
  2097. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2098. {"soft_max", 64}, {"im2col", 64},
  2099. {"argmax", 64}, {"mul_mat_vec", 64},
  2100. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2101. };
  2102. // Pipeline configuration for RDNA2 GPUs.
  2103. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2104. {"soft_max", 64}, {"im2col", 64},
  2105. };
  2106. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2107. // Define configurations for different GPUs.
  2108. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2109. {
  2110. vk_device_architecture::AMD_RDNA1,
  2111. {
  2112. rdna1_pipelines,
  2113. },
  2114. RDNA_DEFAULT_SUBGROUP_SIZE
  2115. },
  2116. {
  2117. vk_device_architecture::AMD_RDNA2,
  2118. {
  2119. rdna2_pipelines,
  2120. },
  2121. RDNA_DEFAULT_SUBGROUP_SIZE
  2122. },
  2123. };
  2124. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2125. for (const auto &config : gpu_pipeline_configs) {
  2126. if (config.arch == arch) {
  2127. auto pipIt = config.pipelines.find(pipeline_name);
  2128. if (pipIt != config.pipelines.end()) {
  2129. return pipIt->second;
  2130. }
  2131. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2132. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2133. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2134. for (const auto &entry : sorted_pipelines) {
  2135. if (pipeline_name.find(entry.first) != std::string::npos) {
  2136. return entry.second;
  2137. }
  2138. }
  2139. return config.default_subgroup_size;
  2140. }
  2141. }
  2142. return 0; // If no matching configuration is found
  2143. }
  2144. static void ggml_vk_load_shaders(vk_device& device) {
  2145. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2146. // some shaders have a minimum subgroup size
  2147. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2148. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2149. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2150. 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;
  2151. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2152. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2153. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2154. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2155. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2156. // mulmat
  2157. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2158. l_warptile_id, m_warptile_id, s_warptile_id,
  2159. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2160. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2161. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2162. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2163. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2164. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2165. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2166. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2167. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2168. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2169. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2170. uint32_t l_align, m_align, s_align;
  2171. if (device->coopmat2) {
  2172. // spec constants and tile sizes for non-quant matmul/matmul_id
  2173. l_warptile = { 256, 128, 256, 64, 1 };
  2174. m_warptile = { 256, 128, 128, 64, 0 };
  2175. s_warptile = { 128, 64, 64, 64, 0 };
  2176. l_wg_denoms = {128, 256, 1 };
  2177. m_wg_denoms = {128, 128, 1 };
  2178. s_wg_denoms = { 64, 64, 1 };
  2179. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2180. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2181. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2182. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2183. l_mmq_wg_denoms = { 128, 256, 1 };
  2184. m_mmq_wg_denoms = { 128, 128, 1 };
  2185. s_mmq_wg_denoms = { 32, 64, 1 };
  2186. // spec constants and tile sizes for quant matmul (Qi_K)
  2187. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2188. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2189. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2190. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2191. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2192. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2193. // spec constants and tile sizes for quant matmul_id
  2194. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2195. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2196. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2197. l_mmqid_wg_denoms = { 128, 128, 1 };
  2198. m_mmqid_wg_denoms = { 128, 64, 1 };
  2199. s_mmqid_wg_denoms = { 128, 64, 1 };
  2200. l_align = 128;
  2201. m_align = 64;
  2202. s_align = 32;
  2203. } else {
  2204. // Matrix cores require different warp group sizes
  2205. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2206. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2207. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2208. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2209. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2210. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2211. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2212. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2213. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2214. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2215. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2216. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2217. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2218. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2219. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2220. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2221. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2222. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2223. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2224. // K-quants use even more registers, mitigate by setting WMITER to 1
  2225. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2226. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2227. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2228. 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 };
  2229. 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 };
  2230. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2231. 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 };
  2232. 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 };
  2233. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2234. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2235. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2236. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2237. 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 };
  2238. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2239. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2240. // chip specific tuning
  2241. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2242. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2243. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2244. }
  2245. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2246. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2247. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2248. l_align = 128;
  2249. m_align = 64;
  2250. s_align = 32;
  2251. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2252. ggml_type t = (ggml_type)i;
  2253. // Disable medium and large matrix multiplication if not enough shared memory is available
  2254. // Check mmq warptiles as the largest configuration
  2255. // Throw an error if not enough for any matrix multiplication is available
  2256. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2257. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2258. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2259. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2260. device->mul_mat_m[i] = false;
  2261. device->mul_mat_l[i] = false;
  2262. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2263. device->mul_mat_l[i] = false;
  2264. }
  2265. // Disable mul_mat_id if not enough shared memory is available
  2266. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2267. device->mul_mat_id_s[i] = false;
  2268. device->mul_mat_id_m[i] = false;
  2269. device->mul_mat_id_l[i] = false;
  2270. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2271. device->mul_mat_id_m[i] = false;
  2272. device->mul_mat_id_l[i] = false;
  2273. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2274. device->mul_mat_id_l[i] = false;
  2275. }
  2276. }
  2277. }
  2278. if (!device->pipeline_matmul_f32) {
  2279. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2280. }
  2281. if (!device->pipeline_matmul_f32_f16) {
  2282. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2283. }
  2284. if (!device->pipeline_matmul_id_f32) {
  2285. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2286. }
  2287. if (!device->pipeline_matmul_bf16) {
  2288. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2289. }
  2290. if (!device->pipeline_matmul_id_bf16) {
  2291. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2292. }
  2293. std::vector<std::future<void>> compiles;
  2294. 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,
  2295. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2296. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2297. if (!require_full_subgroups && required_subgroup_size == 0) {
  2298. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2299. }
  2300. if (!pipeline) {
  2301. pipeline = std::make_shared<vk_pipeline_struct>();
  2302. }
  2303. if (!pipeline->initialized) {
  2304. pipeline->name = name;
  2305. pipeline->parameter_count = parameter_count;
  2306. pipeline->push_constant_size = push_constant_size;
  2307. pipeline->wg_denoms = wg_denoms;
  2308. pipeline->align = align;
  2309. pipeline->initialized = true;
  2310. }
  2311. if (!pipeline->needed || pipeline->compiled) {
  2312. return;
  2313. }
  2314. {
  2315. // wait until fewer than N compiles are in progress
  2316. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2317. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2318. while (compile_count >= N) {
  2319. compile_count_cond.wait(guard);
  2320. }
  2321. compile_count++;
  2322. }
  2323. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2324. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2325. };
  2326. 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,
  2327. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2328. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2329. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2330. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2331. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2332. };
  2333. auto const &fa_wg_denoms = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  2334. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2335. };
  2336. auto const &fa_spec_constants = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  2337. // For large number of rows, 128 invocations seems to work best.
  2338. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2339. // can't use 256 for D==80.
  2340. // For scalar, use 128 (arbitrary)
  2341. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2342. const uint32_t D = (hsk|hsv);
  2343. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2344. ? scalar_flash_attention_workgroup_size
  2345. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2346. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2347. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2348. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2349. const uint32_t D_lsb = D ^ (D & (D-1));
  2350. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2351. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2352. };
  2353. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2354. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2355. uint32_t HSK = fa.first.HSK; \
  2356. uint32_t HSV = fa.first.HSV; \
  2357. bool small_rows = fa.first.small_rows; \
  2358. FaCodePath path = fa.first.path; \
  2359. bool aligned = fa.first.aligned; \
  2360. bool f32acc = fa.first.f32acc; \
  2361. if (path == FAPATH) { \
  2362. if (aligned) { \
  2363. if (f32acc) { \
  2364. 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), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2365. } else { \
  2366. 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), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2367. } \
  2368. } else { \
  2369. if (f32acc) { \
  2370. 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), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2371. } else { \
  2372. 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), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2373. } \
  2374. } \
  2375. } \
  2376. }
  2377. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2378. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2379. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2380. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2381. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2382. if (device->coopmat1_fa_support) {
  2383. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2384. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2385. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2386. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2387. }
  2388. #endif
  2389. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2390. if (device->coopmat2) {
  2391. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2392. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2393. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2394. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2395. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2396. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2397. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2398. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2399. }
  2400. #endif
  2401. #undef CREATE_FA
  2402. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2403. if (device->coopmat2) {
  2404. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2405. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2406. 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); \
  2407. 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); \
  2408. 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); \
  2409. 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); \
  2410. 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); \
  2411. 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); \
  2412. // Create 2 variants, {f16,f32} accumulator
  2413. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2414. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2415. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2416. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2417. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2418. if (device->coopmat_bf16_support) {
  2419. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2420. }
  2421. #endif
  2422. 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)
  2423. 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)
  2424. 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)
  2425. 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)
  2426. 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)
  2427. 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)
  2428. 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)
  2429. 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)
  2430. 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)
  2431. 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)
  2432. 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)
  2433. 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)
  2434. 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)
  2435. 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)
  2436. 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)
  2437. 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)
  2438. 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)
  2439. 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)
  2440. 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)
  2441. 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)
  2442. GGML_ASSERT(device->subgroup_ballot);
  2443. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2444. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2445. if (device->coopmat_bf16_support) {
  2446. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2447. }
  2448. #endif
  2449. 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, 4)
  2450. 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, 4)
  2451. 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, 4)
  2452. 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, 4)
  2453. 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, 4)
  2454. 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, 4)
  2455. 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, 4)
  2456. 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, 4)
  2457. 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, 4)
  2458. 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, 4)
  2459. 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, 4)
  2460. 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, 4)
  2461. 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, 4)
  2462. 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, 4)
  2463. 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, 4)
  2464. 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, 4)
  2465. 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, 4)
  2466. 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, 4)
  2467. 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, 4)
  2468. 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, 4)
  2469. #undef CREATE_MM
  2470. #undef CREATE_MM2
  2471. } else
  2472. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2473. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2474. if (device->coopmat_support) {
  2475. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2476. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2477. if (device->mul_mat ## ID ## _l[TYPE]) \
  2478. 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); \
  2479. if (device->mul_mat ## ID ## _m[TYPE]) \
  2480. 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); \
  2481. if (device->mul_mat ## ID ## _s[TYPE]) \
  2482. 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); \
  2483. if (device->mul_mat ## ID ## _l[TYPE]) \
  2484. 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); \
  2485. if (device->mul_mat ## ID ## _m[TYPE]) \
  2486. 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); \
  2487. if (device->mul_mat ## ID ## _s[TYPE]) \
  2488. 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); \
  2489. // Create 2 variants, {f16,f32} accumulator
  2490. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2491. if (device->coopmat_acc_f16_support) { \
  2492. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2493. } \
  2494. if (device->coopmat_acc_f32_support) { \
  2495. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2496. } \
  2497. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2498. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2499. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2500. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2501. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2502. if (device->coopmat_bf16_support) {
  2503. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2504. }
  2505. #endif
  2506. if (device->coopmat_acc_f16_support) {
  2507. 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, );
  2508. 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, );
  2509. 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, );
  2510. 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, );
  2511. 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, );
  2512. 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, );
  2513. 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, );
  2514. 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, );
  2515. 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, );
  2516. 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, );
  2517. 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, );
  2518. 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, );
  2519. 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, );
  2520. 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, );
  2521. 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, );
  2522. 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, );
  2523. 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, );
  2524. 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, );
  2525. 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, );
  2526. 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, );
  2527. } else {
  2528. 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, );
  2529. 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, );
  2530. 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, );
  2531. 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, );
  2532. 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, );
  2533. 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, );
  2534. 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, );
  2535. 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, );
  2536. 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, );
  2537. 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, );
  2538. 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, );
  2539. 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, );
  2540. 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, );
  2541. 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, );
  2542. 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, );
  2543. 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, );
  2544. 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, );
  2545. 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, );
  2546. 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, );
  2547. 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, );
  2548. }
  2549. GGML_ASSERT(device->subgroup_ballot);
  2550. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2551. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2552. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2553. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2554. if (device->coopmat_bf16_support) {
  2555. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2556. }
  2557. #endif
  2558. 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, 4, _id);
  2559. 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, 4, _id);
  2560. 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, 4, _id);
  2561. 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, 4, _id);
  2562. 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, 4, _id);
  2563. 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, 4, _id);
  2564. 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, 4, _id);
  2565. 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, 4, _id);
  2566. 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, 4, _id);
  2567. 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, 4, _id);
  2568. 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, 4, _id);
  2569. 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, 4, _id);
  2570. 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, 4, _id);
  2571. 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, 4, _id);
  2572. 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, 4, _id);
  2573. 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, 4, _id);
  2574. 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, 4, _id);
  2575. 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, 4, _id);
  2576. 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, 4, _id);
  2577. 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, 4, _id);
  2578. #undef CREATE_MM2
  2579. #undef CREATE_MM
  2580. } else
  2581. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2582. if (device->fp16) {
  2583. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2584. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2585. if (device->mul_mat ## ID ## _l[TYPE]) \
  2586. 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); \
  2587. if (device->mul_mat ## ID ## _m[TYPE]) \
  2588. 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); \
  2589. if (device->mul_mat ## ID ## _s[TYPE]) \
  2590. 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); \
  2591. if (device->mul_mat ## ID ## _l[TYPE]) \
  2592. 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); \
  2593. if (device->mul_mat ## ID ## _m[TYPE]) \
  2594. 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); \
  2595. if (device->mul_mat ## ID ## _s[TYPE]) \
  2596. 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); \
  2597. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2598. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2599. 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); \
  2600. } \
  2601. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2602. 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); \
  2603. } \
  2604. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2605. 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); \
  2606. } \
  2607. // Create 2 variants, {f16,f32} accumulator
  2608. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2609. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2610. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2611. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2612. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2613. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2614. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2615. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2616. 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);
  2617. 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);
  2618. 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);
  2619. 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);
  2620. 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);
  2621. 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);
  2622. 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);
  2623. 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);
  2624. 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);
  2625. 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);
  2626. 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);
  2627. 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);
  2628. 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);
  2629. 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);
  2630. 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);
  2631. 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);
  2632. 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);
  2633. 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);
  2634. 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);
  2635. 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);
  2636. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2637. if (device->integer_dot_product) {
  2638. 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);
  2639. 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);
  2640. 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);
  2641. 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);
  2642. 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);
  2643. 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);
  2644. 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);
  2645. 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);
  2646. 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);
  2647. 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);
  2648. 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);
  2649. }
  2650. #endif
  2651. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2652. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2653. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2654. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2655. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2656. 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, 4, _id, mul_mat_subgroup_size);
  2657. 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, 4, _id, mul_mat_subgroup_size);
  2658. 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, 4, _id, mul_mat_subgroup_size);
  2659. 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, 4, _id, mul_mat_subgroup_size);
  2660. 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, 4, _id, mul_mat_subgroup_size);
  2661. 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, 4, _id, mul_mat_subgroup_size);
  2662. 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, 4, _id, mul_mat_subgroup_size);
  2663. 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, 4, _id, mul_mat_subgroup_size);
  2664. 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, 4, _id, mul_mat_subgroup_size);
  2665. 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, 4, _id, mul_mat_subgroup_size);
  2666. 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, 4, _id, mul_mat_subgroup_size);
  2667. 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, 4, _id, mul_mat_subgroup_size);
  2668. 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, 4, _id, mul_mat_subgroup_size);
  2669. 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, 4, _id, mul_mat_subgroup_size);
  2670. 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, 4, _id, mul_mat_subgroup_size);
  2671. 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, 4, _id, mul_mat_subgroup_size);
  2672. 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, 4, _id, mul_mat_subgroup_size);
  2673. 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, 4, _id, mul_mat_subgroup_size);
  2674. 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, 4, _id, mul_mat_subgroup_size);
  2675. 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, 4, _id, mul_mat_subgroup_size);
  2676. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2677. if (device->integer_dot_product) {
  2678. 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, 4, _id, mul_mat_subgroup_size);
  2679. 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, 4, _id, mul_mat_subgroup_size);
  2680. 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, 4, _id, mul_mat_subgroup_size);
  2681. 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, 4, _id, mul_mat_subgroup_size);
  2682. 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, 4, _id, mul_mat_subgroup_size);
  2683. 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, 4, _id, mul_mat_subgroup_size);
  2684. 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, 4, _id, mul_mat_subgroup_size_16);
  2685. 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, 4, _id, mul_mat_subgroup_size_16);
  2686. 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, 4, _id, mul_mat_subgroup_size_16);
  2687. 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, 4, _id, mul_mat_subgroup_size_16);
  2688. 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, 4, _id, mul_mat_subgroup_size_16);
  2689. }
  2690. #endif
  2691. } else {
  2692. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2693. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2694. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2695. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2696. 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, 4, _id, 0);
  2697. 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, 4, _id, 0);
  2698. 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, 4, _id, 0);
  2699. 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, 4, _id, 0);
  2700. 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, 4, _id, 0);
  2701. 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, 4, _id, 0);
  2702. 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, 4, _id, 0);
  2703. 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, 4, _id, 0);
  2704. 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, 4, _id, 0);
  2705. 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, 4, _id, 0);
  2706. 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, 4, _id, 0);
  2707. 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, 4, _id, 0);
  2708. 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, 4, _id, 0);
  2709. 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, 4, _id, 0);
  2710. 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, 4, _id, 0);
  2711. 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, 4, _id, 0);
  2712. 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, 4, _id, 0);
  2713. 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, 4, _id, 0);
  2714. 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, 4, _id, 0);
  2715. 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, 4, _id, 0);
  2716. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2717. if (device->integer_dot_product) {
  2718. 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, 4, _id, 0);
  2719. 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, 4, _id, 0);
  2720. 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, 4, _id, 0);
  2721. 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, 4, _id, 0);
  2722. 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, 4, _id, 0);
  2723. 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, 4, _id, 0);
  2724. 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, 4, _id, 0);
  2725. 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, 4, _id, 0);
  2726. 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, 4, _id, 0);
  2727. 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, 4, _id, 0);
  2728. 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, 4, _id, 0);
  2729. }
  2730. #endif
  2731. }
  2732. #undef CREATE_MM2
  2733. #undef CREATE_MMQ
  2734. #undef CREATE_MM
  2735. } else {
  2736. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2737. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2738. if (device->mul_mat ## ID ## _l[TYPE]) \
  2739. 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); \
  2740. if (device->mul_mat ## ID ## _m[TYPE]) \
  2741. 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); \
  2742. if (device->mul_mat ## ID ## _s[TYPE]) \
  2743. 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); \
  2744. if (device->mul_mat ## ID ## _l[TYPE]) \
  2745. 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); \
  2746. if (device->mul_mat ## ID ## _m[TYPE]) \
  2747. 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); \
  2748. if (device->mul_mat ## ID ## _s[TYPE]) \
  2749. 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); \
  2750. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2751. if (device->mul_mat ## ID ## _l[TYPE]) \
  2752. 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); \
  2753. if (device->mul_mat ## ID ## _m[TYPE]) \
  2754. 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); \
  2755. if (device->mul_mat ## ID ## _s[TYPE]) \
  2756. 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); \
  2757. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2758. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2759. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2760. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2761. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2762. 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);
  2763. 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);
  2764. 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);
  2765. 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);
  2766. 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);
  2767. 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);
  2768. 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);
  2769. 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);
  2770. 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);
  2771. 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);
  2772. 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);
  2773. 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);
  2774. 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);
  2775. 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);
  2776. 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);
  2777. 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);
  2778. 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);
  2779. 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);
  2780. 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);
  2781. 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);
  2782. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2783. if (device->integer_dot_product) {
  2784. 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, );
  2785. 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, );
  2786. 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, );
  2787. 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, );
  2788. 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, );
  2789. 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, );
  2790. 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, );
  2791. 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, );
  2792. 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, );
  2793. 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, );
  2794. }
  2795. #endif
  2796. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2797. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2798. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2799. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2800. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2801. 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, 4, _id, mul_mat_subgroup_size);
  2802. 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, 4, _id, mul_mat_subgroup_size);
  2803. 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, 4, _id, mul_mat_subgroup_size);
  2804. 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, 4, _id, mul_mat_subgroup_size);
  2805. 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, 4, _id, mul_mat_subgroup_size);
  2806. 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, 4, _id, mul_mat_subgroup_size);
  2807. 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, 4, _id, mul_mat_subgroup_size);
  2808. 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, 4, _id, mul_mat_subgroup_size);
  2809. 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, 4, _id, mul_mat_subgroup_size);
  2810. 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, 4, _id, mul_mat_subgroup_size);
  2811. 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, 4, _id, mul_mat_subgroup_size);
  2812. 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, 4, _id, mul_mat_subgroup_size);
  2813. 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, 4, _id, mul_mat_subgroup_size);
  2814. 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, 4, _id, mul_mat_subgroup_size);
  2815. 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, 4, _id, mul_mat_subgroup_size);
  2816. 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, 4, _id, mul_mat_subgroup_size);
  2817. 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, 4, _id, mul_mat_subgroup_size);
  2818. 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, 4, _id, mul_mat_subgroup_size);
  2819. 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, 4, _id, mul_mat_subgroup_size);
  2820. 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, 4, _id, mul_mat_subgroup_size);
  2821. } else {
  2822. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2823. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2824. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2825. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2826. 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, 4, _id, 0);
  2827. 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, 4, _id, 0);
  2828. 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, 4, _id, 0);
  2829. 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, 4, _id, 0);
  2830. 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, 4, _id, 0);
  2831. 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, 4, _id, 0);
  2832. 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, 4, _id, 0);
  2833. 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, 4, _id, 0);
  2834. 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, 4, _id, 0);
  2835. 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, 4, _id, 0);
  2836. 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, 4, _id, 0);
  2837. 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, 4, _id, 0);
  2838. 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, 4, _id, 0);
  2839. 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, 4, _id, 0);
  2840. 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, 4, _id, 0);
  2841. 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, 4, _id, 0);
  2842. 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, 4, _id, 0);
  2843. 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, 4, _id, 0);
  2844. 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, 4, _id, 0);
  2845. 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, 4, _id, 0);
  2846. }
  2847. }
  2848. // reusing CREATE_MM from the fp32 path
  2849. if ((device->coopmat2 || device->coopmat_support)
  2850. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2851. && !device->coopmat_bf16_support
  2852. #endif
  2853. ) {
  2854. // use scalar tile sizes
  2855. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2856. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2857. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2858. l_wg_denoms = {128, 128, 1 };
  2859. m_wg_denoms = { 64, 64, 1 };
  2860. s_wg_denoms = { 32, 32, 1 };
  2861. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2862. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2863. }
  2864. #undef CREATE_MM
  2865. // mul mat vec
  2866. // the number of rows computed per shader depends on GPU model and quant
  2867. uint32_t rm_stdq = 1;
  2868. uint32_t rm_kq = 2;
  2869. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2870. if (device->architecture == AMD_GCN) {
  2871. rm_stdq = 2;
  2872. rm_kq = 4;
  2873. }
  2874. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2875. rm_stdq = 2;
  2876. uint32_t rm_iq = 2 * rm_kq;
  2877. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  2878. // Ensure a subgroup size >= 16 is available
  2879. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  2880. 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;
  2881. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  2882. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  2883. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  2884. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  2885. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  2886. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  2887. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2888. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2889. SHADER_REDUCTION_MODE_SHMEM;
  2890. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2891. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2892. SHADER_REDUCTION_MODE_SHMEM;
  2893. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  2894. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2895. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2896. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2897. 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", 4, 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);
  2898. 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", 4, 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);
  2899. 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", 4, 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);
  2900. 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", 4, 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);
  2901. 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", 4, 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);
  2902. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2903. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2904. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2905. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2906. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2907. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2908. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2909. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2910. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2911. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2912. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2913. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2914. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2915. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2916. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2917. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2918. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2919. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2920. 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", 4, 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);
  2921. 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", 4, 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);
  2922. 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", 4, 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);
  2923. 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", 4, 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);
  2924. 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", 4, 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);
  2925. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2926. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2927. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2928. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2929. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2930. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2931. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2932. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2933. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2934. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2935. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2936. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2937. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2938. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2939. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2940. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2941. if (device->integer_dot_product) {
  2942. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2943. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  2944. 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", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2945. 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", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2946. 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", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2947. 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", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2948. 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", 4, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2949. }
  2950. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  2951. }
  2952. }
  2953. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", mul_mat_vec_id_f32_f32_len, mul_mat_vec_id_f32_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2954. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", mul_mat_vec_id_f16_f32_len, mul_mat_vec_id_f16_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2955. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", mul_mat_vec_id_bf16_f32_len, mul_mat_vec_id_bf16_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2956. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", mul_mat_vec_id_q4_0_f32_len, mul_mat_vec_id_q4_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2957. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", mul_mat_vec_id_q4_1_f32_len, mul_mat_vec_id_q4_1_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2958. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", mul_mat_vec_id_q5_0_f32_len, mul_mat_vec_id_q5_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2959. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", mul_mat_vec_id_q5_1_f32_len, mul_mat_vec_id_q5_1_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2960. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", mul_mat_vec_id_q8_0_f32_len, mul_mat_vec_id_q8_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq}, 1, true);
  2961. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", mul_mat_vec_id_q2_k_f32_len, mul_mat_vec_id_q2_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2962. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", mul_mat_vec_id_q3_k_f32_len, mul_mat_vec_id_q3_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2963. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", mul_mat_vec_id_q4_k_f32_len, mul_mat_vec_id_q4_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2964. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", mul_mat_vec_id_q5_k_f32_len, mul_mat_vec_id_q5_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2965. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", mul_mat_vec_id_q6_k_f32_len, mul_mat_vec_id_q6_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2966. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", mul_mat_vec_id_iq1_s_f32_len, mul_mat_vec_id_iq1_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2967. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", mul_mat_vec_id_iq1_m_f32_len, mul_mat_vec_id_iq1_m_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2968. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", mul_mat_vec_id_iq2_xxs_f32_len, mul_mat_vec_id_iq2_xxs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2969. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", mul_mat_vec_id_iq2_xs_f32_len, mul_mat_vec_id_iq2_xs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2970. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", mul_mat_vec_id_iq2_s_f32_len, mul_mat_vec_id_iq2_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2971. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", mul_mat_vec_id_iq3_xxs_f32_len, mul_mat_vec_id_iq3_xxs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2972. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", mul_mat_vec_id_iq3_s_f32_len, mul_mat_vec_id_iq3_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2973. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", mul_mat_vec_id_iq4_xs_f32_len, mul_mat_vec_id_iq4_xs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2974. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", mul_mat_vec_id_iq4_nl_f32_len, mul_mat_vec_id_iq4_nl_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2975. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", mul_mat_vec_id_mxfp4_f32_len, mul_mat_vec_id_mxfp4_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2976. // dequant shaders
  2977. 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);
  2978. 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);
  2979. 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);
  2980. 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);
  2981. 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);
  2982. 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);
  2983. 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);
  2984. 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);
  2985. 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);
  2986. 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);
  2987. 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);
  2988. 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);
  2989. 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);
  2990. 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);
  2991. 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);
  2992. 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);
  2993. 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);
  2994. 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);
  2995. 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);
  2996. 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);
  2997. 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);
  2998. // get_rows
  2999. 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);
  3000. 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);
  3001. 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);
  3002. 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);
  3003. 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);
  3004. 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);
  3005. 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);
  3006. 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);
  3007. 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);
  3008. 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);
  3009. 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);
  3010. 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);
  3011. 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);
  3012. 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);
  3013. 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);
  3014. 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);
  3015. 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);
  3016. 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);
  3017. 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);
  3018. 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);
  3019. 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);
  3020. 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);
  3021. 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);
  3022. 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);
  3023. 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);
  3024. 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);
  3025. 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);
  3026. 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);
  3027. 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);
  3028. 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);
  3029. 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);
  3030. 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);
  3031. 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);
  3032. 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);
  3033. 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);
  3034. 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);
  3035. 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);
  3036. 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);
  3037. 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);
  3038. 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);
  3039. 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);
  3040. 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);
  3041. 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);
  3042. 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);
  3043. 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);
  3044. 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);
  3045. 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);
  3046. 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);
  3047. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3048. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1, "quantize_q8_1", quantize_q8_1_subgroup_len, quantize_q8_1_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3049. 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, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3050. } else {
  3051. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1, "quantize_q8_1", quantize_q8_1_len, quantize_q8_1_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3052. 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, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3053. }
  3054. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3055. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3056. 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", 4, 7 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  3057. } else {
  3058. 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", 4, 7 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  3059. }
  3060. }
  3061. 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", 4, 13 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  3062. 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);
  3063. 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);
  3064. 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);
  3065. 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);
  3066. 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);
  3067. 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);
  3068. 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);
  3069. 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);
  3070. 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);
  3071. 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);
  3072. 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);
  3073. 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);
  3074. 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);
  3075. 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);
  3076. 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);
  3077. 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);
  3078. 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);
  3079. 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);
  3080. 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);
  3081. 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);
  3082. 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);
  3083. 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);
  3084. if (device->float_controls_rte_fp16) {
  3085. 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);
  3086. 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);
  3087. 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);
  3088. 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);
  3089. 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);
  3090. 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);
  3091. } else {
  3092. 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);
  3093. 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);
  3094. 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);
  3095. 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);
  3096. 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);
  3097. 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);
  3098. }
  3099. #define SET_ROWS(itype, rte) \
  3100. 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); \
  3101. 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); \
  3102. 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); \
  3103. 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); \
  3104. 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); \
  3105. 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); \
  3106. 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); \
  3107. 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); \
  3108. 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);
  3109. if (device->float_controls_rte_fp16) {
  3110. SET_ROWS(_i32, _rte)
  3111. SET_ROWS(_i64, _rte)
  3112. } else {
  3113. SET_ROWS(_i32, )
  3114. SET_ROWS(_i64, )
  3115. }
  3116. #undef SET_ROWS
  3117. 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);
  3118. 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);
  3119. 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);
  3120. 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);
  3121. 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);
  3122. 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);
  3123. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3124. std::string s;
  3125. s += std::string(src0_f16 ? "_f16" : "_f32");
  3126. s += std::string(src1_f16 ? "_f16" : "_f32");
  3127. s += std::string(dst_f16 ? "_f16" : "_f32");
  3128. return s;
  3129. };
  3130. bool rte = device->float_controls_rte_fp16;
  3131. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3132. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3133. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3134. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3135. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3136. CREATE_BINARY(add, , {0}, 4)
  3137. CREATE_BINARY(add, _norepeat, {1}, 4)
  3138. CREATE_BINARY(sub, , {0}, 3)
  3139. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3140. CREATE_BINARY(mul, , {0}, 3)
  3141. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3142. CREATE_BINARY(div, , {0}, 3)
  3143. CREATE_BINARY(div, _norepeat, {1}, 3)
  3144. CREATE_BINARY(add_rms, , {0}, 4)
  3145. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3146. #undef CREATE_BINARY
  3147. if (device->multi_add) {
  3148. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3149. 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);
  3150. 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);
  3151. }
  3152. }
  3153. 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);
  3154. 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);
  3155. 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);
  3156. 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);
  3157. 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);
  3158. 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);
  3159. 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);
  3160. 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);
  3161. 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);
  3162. 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);
  3163. 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);
  3164. 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);
  3165. 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);
  3166. 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);
  3167. 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);
  3168. 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);
  3169. 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);
  3170. #define CREATE_UNARY(name) \
  3171. 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); \
  3172. 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);
  3173. CREATE_UNARY(gelu)
  3174. CREATE_UNARY(gelu_erf)
  3175. CREATE_UNARY(gelu_quick)
  3176. CREATE_UNARY(silu)
  3177. CREATE_UNARY(relu)
  3178. CREATE_UNARY(tanh)
  3179. CREATE_UNARY(sigmoid)
  3180. CREATE_UNARY(hardsigmoid)
  3181. CREATE_UNARY(hardswish)
  3182. #undef CREATE_UNARY
  3183. #define CREATE_UNARY_RTE(name) \
  3184. if (device->float_controls_rte_fp16) { \
  3185. 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); \
  3186. 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); \
  3187. } else { \
  3188. 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); \
  3189. 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); \
  3190. }
  3191. CREATE_UNARY_RTE(exp)
  3192. #undef CREATE_UNARY_RTE
  3193. #define CREATE_GLU(name) \
  3194. if (device->float_controls_rte_fp16) { \
  3195. 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); \
  3196. 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); \
  3197. } else { \
  3198. 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); \
  3199. 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); \
  3200. }
  3201. CREATE_GLU(geglu)
  3202. CREATE_GLU(reglu)
  3203. CREATE_GLU(swiglu)
  3204. CREATE_GLU(swiglu_oai)
  3205. CREATE_GLU(geglu_erf)
  3206. CREATE_GLU(geglu_quick)
  3207. #undef CREATE_GLU
  3208. 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);
  3209. 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);
  3210. 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);
  3211. 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);
  3212. 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);
  3213. 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);
  3214. 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);
  3215. 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);
  3216. 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);
  3217. 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);
  3218. 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);
  3219. 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);
  3220. if (device->float_controls_rte_fp16) {
  3221. 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);
  3222. 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);
  3223. 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);
  3224. 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);
  3225. 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);
  3226. 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);
  3227. } else {
  3228. 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);
  3229. 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);
  3230. 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);
  3231. 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);
  3232. 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);
  3233. 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);
  3234. }
  3235. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3236. ggml_vk_create_pipeline2(device, device->pipeline_argsort_f32[i], "argsort_f32_"+std::to_string(i), argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1u<<i, 1, 1}, {1u<<i, i}, 1, true);
  3237. }
  3238. 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);
  3239. 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);
  3240. 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);
  3241. #define IM2COL(bda) \
  3242. 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); \
  3243. 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); \
  3244. if (device->float_controls_rte_fp16) { \
  3245. 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); \
  3246. 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); \
  3247. } else { \
  3248. 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); \
  3249. 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); \
  3250. }
  3251. if (device->shader_int64 && device->buffer_device_address) {
  3252. IM2COL(_bda)
  3253. } else {
  3254. IM2COL()
  3255. }
  3256. 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);
  3257. 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);
  3258. 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);
  3259. 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);
  3260. 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);
  3261. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3262. 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, 16}, 1, true, true);
  3263. 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, 16}, 1, true, true);
  3264. } else {
  3265. 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);
  3266. 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);
  3267. }
  3268. 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);
  3269. 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);
  3270. 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);
  3271. // conv2d, conv_transpose_2d
  3272. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3273. uint32_t conv2d_WG_SIZE = 256;
  3274. uint32_t conv2d_BS_K = 128;
  3275. uint32_t conv2d_BS_CRS = 16;
  3276. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3277. uint32_t conv2d_BS_NPQ = 128;
  3278. uint32_t conv2d_TS_K = 8;
  3279. uint32_t conv2d_SHMEM_PAD = 4;
  3280. bool conv2d_UNROLL = true;
  3281. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3282. if (device->coopmat2) {
  3283. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3284. }
  3285. #endif
  3286. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3287. conv2d_SHMEM_PAD = 0;
  3288. conv2d_UNROLL = false;
  3289. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3290. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3291. }
  3292. switch (s) {
  3293. default:
  3294. case CONV_SHAPE_128x128:
  3295. conv2d_BS_K = 128;
  3296. conv2d_BS_NPQ = 128;
  3297. conv2d_BS_CRS = 16;
  3298. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  3299. conv2d_UNROLL = false;
  3300. }
  3301. break;
  3302. case CONV_SHAPE_64x32:
  3303. conv2d_BS_K = 64;
  3304. conv2d_BS_NPQ = 32;
  3305. conv2d_BS_CRS = 32;
  3306. conv2d_TS_K = 4;
  3307. break;
  3308. case CONV_SHAPE_32x256:
  3309. conv2d_BS_K = 32;
  3310. conv2d_BS_NPQ = 256;
  3311. conv2d_BS_CRS = 16;
  3312. break;
  3313. }
  3314. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3315. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3316. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3317. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3318. device->architecture == vk_device_architecture::AMD_GCN;
  3319. if (device->subgroup_shuffle &&
  3320. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3321. allow_collectives_nv &&
  3322. allow_collectives_amd) {
  3323. use_collectives = 1;
  3324. conv2d_BS_CRS = std::min(
  3325. device->subgroup_size,
  3326. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3327. }
  3328. uint32_t conv2d_shmem_req =
  3329. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3330. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3331. conv2d_BS_CRS = 8;
  3332. if (use_collectives) {
  3333. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  3334. }
  3335. }
  3336. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  3337. 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 };
  3338. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3339. ggml_vk_create_pipeline( \
  3340. device, device->pipeline_##name##type_suffix[s], #name #type_suffix, \
  3341. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3342. sizeof(vk_op_##name##_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  3343. #define CREATE_CONVS(spv_suffix) \
  3344. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3345. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3346. if (device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_conv_transpose_2d_push_constants)) { \
  3347. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3348. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) \
  3349. }
  3350. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3351. if (device->coopmat2) {
  3352. CREATE_CONVS(_cm2)
  3353. } else
  3354. #endif
  3355. if (conv2d_UNROLL) {
  3356. CREATE_CONVS(_unroll)
  3357. } else {
  3358. CREATE_CONVS( )
  3359. }
  3360. #undef CREATE_CONV
  3361. #undef CREATE_CONVS
  3362. }
  3363. 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);
  3364. 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);
  3365. 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);
  3366. 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);
  3367. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3368. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX], "topk_moe_f32_early_softmax_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 0}, 1, true, true);
  3369. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX_NORM], "topk_moe_f32_early_softmax_norm"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 1, 0}, 1, true, true);
  3370. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_LATE_SOFTMAX], "topk_moe_f32_late_softmax"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 1}, 1, true, true);
  3371. }
  3372. for (auto &c : compiles) {
  3373. c.wait();
  3374. }
  3375. device->need_compiles = false;
  3376. }
  3377. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3378. static vk_device ggml_vk_get_device(size_t idx) {
  3379. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3380. if (vk_instance.devices[idx] == nullptr) {
  3381. VK_LOG_DEBUG("Initializing new vk_device");
  3382. vk_device device = std::make_shared<vk_device_struct>();
  3383. vk_instance.devices[idx] = device;
  3384. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3385. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3386. #endif
  3387. if (vk_perf_logger_enabled) {
  3388. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  3389. }
  3390. size_t dev_num = vk_instance.device_indices[idx];
  3391. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3392. if (dev_num >= physical_devices.size()) {
  3393. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3394. throw std::runtime_error("Device not found");
  3395. }
  3396. device->physical_device = physical_devices[dev_num];
  3397. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3398. device->architecture = get_device_architecture(device->physical_device);
  3399. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3400. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3401. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3402. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3403. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3404. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3405. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3406. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3407. bool fp16_storage = false;
  3408. bool fp16_compute = false;
  3409. bool maintenance4_support = false;
  3410. bool sm_builtins = false;
  3411. bool amd_shader_core_properties2 = false;
  3412. bool pipeline_robustness = false;
  3413. bool coopmat2_support = false;
  3414. bool pipeline_executable_properties_support = false;
  3415. device->coopmat_support = false;
  3416. device->integer_dot_product = false;
  3417. bool bfloat16_support = false;
  3418. for (const auto& properties : ext_props) {
  3419. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3420. maintenance4_support = true;
  3421. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3422. fp16_storage = true;
  3423. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3424. fp16_compute = true;
  3425. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3426. sm_builtins = true;
  3427. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3428. amd_shader_core_properties2 = true;
  3429. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3430. pipeline_robustness = true;
  3431. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3432. device->subgroup_size_control = true;
  3433. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3434. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3435. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3436. device->coopmat_support = true;
  3437. device->coopmat_m = 0;
  3438. device->coopmat_n = 0;
  3439. device->coopmat_k = 0;
  3440. #endif
  3441. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3442. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3443. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3444. coopmat2_support = true;
  3445. #endif
  3446. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3447. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3448. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3449. device->integer_dot_product = true;
  3450. #endif
  3451. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3452. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3453. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3454. bfloat16_support = true;
  3455. #endif
  3456. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3457. pipeline_executable_properties_support = true;
  3458. }
  3459. }
  3460. vk::PhysicalDeviceProperties2 props2;
  3461. vk::PhysicalDeviceMaintenance3Properties props3;
  3462. vk::PhysicalDeviceMaintenance4Properties props4;
  3463. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3464. vk::PhysicalDeviceDriverProperties driver_props;
  3465. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3466. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3467. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3468. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3469. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3470. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3471. props2.pNext = &props3;
  3472. props3.pNext = &subgroup_props;
  3473. subgroup_props.pNext = &driver_props;
  3474. driver_props.pNext = &vk11_props;
  3475. vk11_props.pNext = &vk12_props;
  3476. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3477. if (maintenance4_support) {
  3478. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3479. last_struct = (VkBaseOutStructure *)&props4;
  3480. }
  3481. if (sm_builtins) {
  3482. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3483. last_struct = (VkBaseOutStructure *)&sm_props;
  3484. }
  3485. if (amd_shader_core_properties2) {
  3486. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3487. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3488. }
  3489. if (device->subgroup_size_control) {
  3490. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3491. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3492. }
  3493. #if defined(VK_NV_cooperative_matrix2)
  3494. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3495. if (coopmat2_support) {
  3496. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3497. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3498. }
  3499. #endif
  3500. if (device->integer_dot_product) {
  3501. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3502. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3503. }
  3504. device->physical_device.getProperties2(&props2);
  3505. device->properties = props2.properties;
  3506. device->vendor_id = device->properties.vendorID;
  3507. device->driver_id = driver_props.driverID;
  3508. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3509. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3510. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3511. } else if (maintenance4_support) {
  3512. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3513. } else {
  3514. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3515. }
  3516. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3517. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3518. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3519. } else if (maintenance4_support) {
  3520. device->max_buffer_size = props4.maxBufferSize;
  3521. } else {
  3522. device->max_buffer_size = device->max_memory_allocation_size;
  3523. }
  3524. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3525. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3526. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3527. } else {
  3528. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3529. device->suballocation_block_size = 1024*1024*1024;
  3530. }
  3531. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3532. device->subgroup_size = subgroup_props.subgroupSize;
  3533. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3534. if (sm_builtins) {
  3535. device->shader_core_count = sm_props.shaderSMCount;
  3536. } else if (amd_shader_core_properties2) {
  3537. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3538. } else {
  3539. device->shader_core_count = 0;
  3540. }
  3541. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3542. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3543. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3544. #ifdef __APPLE__
  3545. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3546. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3547. device->subgroup_arithmetic = false;
  3548. }
  3549. #endif
  3550. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3551. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3552. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3553. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3554. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3555. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3556. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3557. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3558. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3559. device->coopmat_support = false;
  3560. }
  3561. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3562. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3563. // Try to find a non-graphics compute queue and transfer-focused queues
  3564. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3565. 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);
  3566. const float priorities[] = { 1.0f, 1.0f };
  3567. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3568. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3569. if (compute_queue_family_index != transfer_queue_family_index) {
  3570. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3571. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3572. } else if(!device->single_queue) {
  3573. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3574. } else {
  3575. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3576. }
  3577. vk::DeviceCreateInfo device_create_info;
  3578. std::vector<const char *> device_extensions;
  3579. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3580. VkPhysicalDeviceFeatures2 device_features2;
  3581. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3582. device_features2.pNext = nullptr;
  3583. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3584. VkPhysicalDeviceVulkan11Features vk11_features;
  3585. vk11_features.pNext = nullptr;
  3586. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3587. device_features2.pNext = &vk11_features;
  3588. VkPhysicalDeviceVulkan12Features vk12_features;
  3589. vk12_features.pNext = nullptr;
  3590. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3591. vk11_features.pNext = &vk12_features;
  3592. last_struct = (VkBaseOutStructure *)&vk12_features;
  3593. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3594. pl_robustness_features.pNext = nullptr;
  3595. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3596. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3597. if (pipeline_robustness) {
  3598. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3599. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3600. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3601. }
  3602. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3603. subgroup_size_control_features.pNext = nullptr;
  3604. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3605. subgroup_size_control_features.computeFullSubgroups = false;
  3606. subgroup_size_control_features.subgroupSizeControl = false;
  3607. if (device->subgroup_size_control) {
  3608. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3609. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3610. }
  3611. #if defined(VK_KHR_cooperative_matrix)
  3612. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3613. coopmat_features.pNext = nullptr;
  3614. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3615. coopmat_features.cooperativeMatrix = VK_FALSE;
  3616. if (device->coopmat_support) {
  3617. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3618. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3619. }
  3620. #endif
  3621. #if defined(VK_NV_cooperative_matrix2)
  3622. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3623. coopmat2_features.pNext = nullptr;
  3624. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3625. if (coopmat2_support) {
  3626. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3627. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3628. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3629. }
  3630. #endif
  3631. #if defined(VK_KHR_shader_bfloat16)
  3632. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3633. bfloat16_features.pNext = nullptr;
  3634. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3635. if (bfloat16_support) {
  3636. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3637. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3638. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3639. }
  3640. #endif
  3641. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3642. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3643. if (maintenance4_support) {
  3644. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3645. last_struct = (VkBaseOutStructure *)&maint4_features;
  3646. device_extensions.push_back("VK_KHR_maintenance4");
  3647. }
  3648. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3649. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3650. if (device->integer_dot_product) {
  3651. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3652. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3653. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3654. }
  3655. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3656. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3657. if (pipeline_executable_properties_support) {
  3658. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3659. last_struct = (VkBaseOutStructure *)&pep_features;
  3660. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3661. }
  3662. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3663. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3664. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3665. #if defined(VK_KHR_shader_bfloat16)
  3666. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3667. #else
  3668. device->bf16 = false;
  3669. #endif
  3670. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3671. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3672. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3673. vk12_features.runtimeDescriptorArray &&
  3674. device->vendor_id != VK_VENDOR_ID_INTEL &&
  3675. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3676. device->shader_int64 = device_features2.features.shaderInt64;
  3677. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3678. if (device->subgroup_size_control) {
  3679. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3680. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3681. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3682. }
  3683. device->subgroup_size_control = device->subgroup_size_control &&
  3684. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3685. subgroup_size_control_features.subgroupSizeControl;
  3686. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3687. #if defined(VK_KHR_cooperative_matrix)
  3688. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3689. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3690. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3691. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3692. device->subgroup_max_size >= 32;
  3693. #endif
  3694. if (coopmat2_support) {
  3695. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3696. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3697. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3698. coopmat2_features.cooperativeMatrixReductions &&
  3699. coopmat2_features.cooperativeMatrixConversions &&
  3700. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3701. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3702. coopmat2_features.cooperativeMatrixBlockLoads &&
  3703. vk12_features.bufferDeviceAddress) {
  3704. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3705. uint32_t count = 0;
  3706. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3707. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3708. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3709. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3710. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3711. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3712. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3713. flexible_dimensions.resize(count, empty_prop);
  3714. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3715. bool found_fp16_128 = false,
  3716. found_fp16_256 = false,
  3717. found_fp32_128 = false,
  3718. found_fp32_256 = false;
  3719. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3720. // with 32x16x16 and 256 with 32x32x16.
  3721. for (auto &prop : flexible_dimensions) {
  3722. if (prop.saturatingAccumulation == VK_FALSE &&
  3723. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3724. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3725. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3726. if (prop.workgroupInvocations == 128 &&
  3727. prop.MGranularity <= 32 &&
  3728. prop.NGranularity <= 16 &&
  3729. prop.KGranularity <= 16) {
  3730. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3731. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3732. found_fp16_128 = true;
  3733. }
  3734. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3735. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3736. found_fp32_128 = true;
  3737. }
  3738. }
  3739. if (prop.workgroupInvocations == 256 &&
  3740. prop.MGranularity <= 32 &&
  3741. prop.NGranularity <= 32 &&
  3742. prop.KGranularity <= 16) {
  3743. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3744. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3745. found_fp16_256 = true;
  3746. }
  3747. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3748. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3749. found_fp32_256 = true;
  3750. }
  3751. }
  3752. }
  3753. }
  3754. if (found_fp16_128 && found_fp16_256 &&
  3755. found_fp32_128 && found_fp32_256 &&
  3756. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3757. device->coopmat2 = true;
  3758. }
  3759. }
  3760. #endif
  3761. }
  3762. if (!vk11_features.storageBuffer16BitAccess) {
  3763. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3764. throw std::runtime_error("Unsupported device");
  3765. }
  3766. device_extensions.push_back("VK_KHR_16bit_storage");
  3767. #ifdef GGML_VULKAN_VALIDATE
  3768. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3769. #endif
  3770. if (device->fp16) {
  3771. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3772. }
  3773. #if defined(VK_KHR_cooperative_matrix)
  3774. if (device->coopmat_support) {
  3775. // Query supported shapes
  3776. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3777. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3778. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3779. uint32_t cm_props_num;
  3780. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3781. cm_props.resize(cm_props_num);
  3782. for (auto& prop : cm_props) {
  3783. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3784. }
  3785. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3786. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3787. for (auto& prop : cm_props) {
  3788. 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));
  3789. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3790. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3791. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3792. ) {
  3793. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3794. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3795. // coopmat sizes not set yet
  3796. if (device->coopmat_m == 0) {
  3797. device->coopmat_acc_f32_support = true;
  3798. device->coopmat_m = prop.MSize;
  3799. device->coopmat_n = prop.NSize;
  3800. device->coopmat_k = prop.KSize;
  3801. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3802. // Only enable if shape is identical
  3803. device->coopmat_acc_f32_support = true;
  3804. }
  3805. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3806. device->coopmat_support_16x16x16_f32acc = true;
  3807. }
  3808. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3809. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3810. // coopmat sizes not set yet
  3811. if (device->coopmat_m == 0) {
  3812. device->coopmat_acc_f16_support = true;
  3813. device->coopmat_m = prop.MSize;
  3814. device->coopmat_n = prop.NSize;
  3815. device->coopmat_k = prop.KSize;
  3816. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3817. // Only enable if shape is identical
  3818. device->coopmat_acc_f16_support = true;
  3819. }
  3820. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3821. device->coopmat_support_16x16x16_f16acc = true;
  3822. }
  3823. }
  3824. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3825. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3826. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3827. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3828. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  3829. device->coopmat_int_m == 0
  3830. ) {
  3831. device->coopmat_int_support = true;
  3832. device->coopmat_int_m = prop.MSize;
  3833. device->coopmat_int_n = prop.NSize;
  3834. device->coopmat_int_k = prop.KSize;
  3835. }
  3836. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3837. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3838. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3839. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3840. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3841. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3842. ) {
  3843. // coopmat sizes not set yet
  3844. if (device->coopmat_m == 0) {
  3845. device->coopmat_bf16_support = true;
  3846. device->coopmat_m = prop.MSize;
  3847. device->coopmat_n = prop.NSize;
  3848. device->coopmat_k = prop.KSize;
  3849. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3850. // Only enable if shape is identical
  3851. device->coopmat_bf16_support = true;
  3852. }
  3853. }
  3854. #endif
  3855. }
  3856. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  3857. // No suitable matmul mode found
  3858. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  3859. device->coopmat_support = false;
  3860. }
  3861. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3862. device->coopmat_bf16_support = false;
  3863. }
  3864. }
  3865. if (device->coopmat_support) {
  3866. device_extensions.push_back("VK_KHR_cooperative_matrix");
  3867. }
  3868. #if defined(VK_KHR_shader_bfloat16)
  3869. if (device->coopmat_bf16_support) {
  3870. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3871. }
  3872. #endif
  3873. #endif
  3874. device->name = GGML_VK_NAME + std::to_string(idx);
  3875. device_create_info = {
  3876. vk::DeviceCreateFlags(),
  3877. device_queue_create_infos,
  3878. {},
  3879. device_extensions
  3880. };
  3881. device_create_info.setPNext(&device_features2);
  3882. device->device = device->physical_device.createDevice(device_create_info);
  3883. // Queues
  3884. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  3885. // Shaders
  3886. // Disable matmul tile sizes early if performance low or not supported
  3887. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  3888. switch (device->vendor_id) {
  3889. #ifndef GGML_VULKAN_RUN_TESTS
  3890. case VK_VENDOR_ID_AMD:
  3891. case VK_VENDOR_ID_INTEL:
  3892. device->mul_mat_l[i] = false;
  3893. device->mul_mat_m[i] = true;
  3894. device->mul_mat_s[i] = true;
  3895. device->mul_mat_id_l[i] = false;
  3896. device->mul_mat_id_m[i] = true;
  3897. device->mul_mat_id_s[i] = true;
  3898. break;
  3899. case VK_VENDOR_ID_APPLE:
  3900. device->mul_mat_l[i] = false;
  3901. device->mul_mat_m[i] = true;
  3902. device->mul_mat_s[i] = false;
  3903. device->mul_mat_id_l[i] = false;
  3904. device->mul_mat_id_m[i] = true;
  3905. device->mul_mat_id_s[i] = false;
  3906. break;
  3907. #endif
  3908. default:
  3909. device->mul_mat_l[i] = true;
  3910. device->mul_mat_m[i] = true;
  3911. device->mul_mat_s[i] = true;
  3912. device->mul_mat_id_l[i] = true;
  3913. device->mul_mat_id_m[i] = true;
  3914. device->mul_mat_id_s[i] = true;
  3915. break;
  3916. }
  3917. }
  3918. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  3919. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  3920. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  3921. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  3922. dsl_binding_flags.push_back({});
  3923. }
  3924. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  3925. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  3926. {},
  3927. dsl_binding);
  3928. descriptor_set_layout_create_info.setPNext(&dslbfci);
  3929. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  3930. ggml_vk_load_shaders(device);
  3931. if (!device->single_queue) {
  3932. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  3933. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  3934. } else {
  3935. // TODO: Use pointer or reference to avoid copy
  3936. device->transfer_queue.copyFrom(device->compute_queue);
  3937. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  3938. }
  3939. device->buffer_type = {
  3940. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  3941. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  3942. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  3943. };
  3944. device->fence = device->device.createFence({});
  3945. device->idx = idx;
  3946. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  3947. device->add_rms_fusion = !device->disable_fusion &&
  3948. device->subgroup_arithmetic &&
  3949. device->vendor_id != VK_VENDOR_ID_INTEL;
  3950. device->partials_binding_alignment =
  3951. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  3952. device->mmvq_mode = 0;
  3953. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  3954. device->mmvq_mode = -1;
  3955. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  3956. device->mmvq_mode = 1;
  3957. }
  3958. return device;
  3959. }
  3960. return vk_instance.devices[idx];
  3961. }
  3962. static void ggml_vk_print_gpu_info(size_t idx) {
  3963. GGML_ASSERT(idx < vk_instance.device_indices.size());
  3964. size_t dev_num = vk_instance.device_indices[idx];
  3965. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  3966. GGML_ASSERT(vk_instance_initialized);
  3967. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3968. if (dev_num >= devices.size()) {
  3969. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3970. throw std::runtime_error("Device not found");
  3971. }
  3972. vk::PhysicalDevice physical_device = devices[dev_num];
  3973. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  3974. bool fp16_storage = false;
  3975. bool fp16_compute = false;
  3976. bool coopmat_support = false;
  3977. bool coopmat2_support = false;
  3978. bool integer_dot_product = false;
  3979. bool bfloat16_support = false;
  3980. for (auto properties : ext_props) {
  3981. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3982. fp16_storage = true;
  3983. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3984. fp16_compute = true;
  3985. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3986. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3987. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3988. coopmat_support = true;
  3989. #endif
  3990. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3991. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3992. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3993. coopmat2_support = true;
  3994. #endif
  3995. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3996. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3997. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3998. integer_dot_product = true;
  3999. #endif
  4000. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4001. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4002. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4003. bfloat16_support = true;
  4004. #endif
  4005. }
  4006. }
  4007. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4008. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4009. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4010. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4011. vk::PhysicalDeviceProperties2 props2;
  4012. vk::PhysicalDeviceMaintenance3Properties props3;
  4013. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4014. vk::PhysicalDeviceDriverProperties driver_props;
  4015. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4016. props2.pNext = &props3;
  4017. props3.pNext = &subgroup_props;
  4018. subgroup_props.pNext = &driver_props;
  4019. // Pointer to the last chain element
  4020. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4021. if (integer_dot_product) {
  4022. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4023. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4024. }
  4025. physical_device.getProperties2(&props2);
  4026. VkPhysicalDeviceFeatures2 device_features2;
  4027. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4028. device_features2.pNext = nullptr;
  4029. VkPhysicalDeviceVulkan11Features vk11_features;
  4030. vk11_features.pNext = nullptr;
  4031. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4032. device_features2.pNext = &vk11_features;
  4033. VkPhysicalDeviceVulkan12Features vk12_features;
  4034. vk12_features.pNext = nullptr;
  4035. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4036. vk11_features.pNext = &vk12_features;
  4037. // Pointer to the last chain element
  4038. last_struct = (VkBaseOutStructure *)&vk12_features;
  4039. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4040. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4041. coopmat_features.pNext = nullptr;
  4042. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4043. coopmat_features.cooperativeMatrix = VK_FALSE;
  4044. if (coopmat_support) {
  4045. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4046. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4047. }
  4048. #endif
  4049. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4050. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4051. if (integer_dot_product) {
  4052. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4053. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4054. }
  4055. #if defined(VK_KHR_shader_bfloat16)
  4056. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4057. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4058. if (bfloat16_support) {
  4059. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4060. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4061. }
  4062. #endif
  4063. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4064. fp16 = fp16 && vk12_features.shaderFloat16;
  4065. #if defined(VK_KHR_shader_bfloat16)
  4066. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4067. #else
  4068. bool bf16 = false;
  4069. #endif
  4070. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4071. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4072. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4073. integer_dot_product = integer_dot_product
  4074. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4075. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4076. coopmat_support = coopmat_support
  4077. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4078. && coopmat_features.cooperativeMatrix
  4079. #endif
  4080. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4081. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4082. std::string device_name = props2.properties.deviceName.data();
  4083. 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",
  4084. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4085. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4086. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4087. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4088. }
  4089. }
  4090. static bool ggml_vk_instance_validation_ext_available();
  4091. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4092. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4093. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4094. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4095. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4096. return ggml_vk_default_dispatcher_instance;
  4097. }
  4098. static void ggml_vk_instance_init() {
  4099. if (vk_instance_initialized) {
  4100. return;
  4101. }
  4102. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4103. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4104. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4105. uint32_t api_version = vk::enumerateInstanceVersion();
  4106. if (api_version < VK_API_VERSION_1_2) {
  4107. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4108. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4109. }
  4110. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4111. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4112. const bool validation_ext = ggml_vk_instance_validation_ext_available();
  4113. #ifdef __APPLE__
  4114. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4115. #endif
  4116. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4117. std::vector<const char*> layers;
  4118. if (validation_ext) {
  4119. layers.push_back("VK_LAYER_KHRONOS_validation");
  4120. }
  4121. std::vector<const char*> extensions;
  4122. if (validation_ext) {
  4123. extensions.push_back("VK_EXT_validation_features");
  4124. }
  4125. #ifdef __APPLE__
  4126. if (portability_enumeration_ext) {
  4127. extensions.push_back("VK_KHR_portability_enumeration");
  4128. }
  4129. #endif
  4130. if (debug_utils_ext) {
  4131. extensions.push_back("VK_EXT_debug_utils");
  4132. }
  4133. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  4134. #ifdef __APPLE__
  4135. if (portability_enumeration_ext) {
  4136. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4137. }
  4138. #endif
  4139. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  4140. vk::ValidationFeaturesEXT validation_features;
  4141. if (validation_ext) {
  4142. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  4143. validation_features = {
  4144. features_enable,
  4145. {},
  4146. };
  4147. validation_features.setPNext(nullptr);
  4148. instance_create_info.setPNext(&validation_features);
  4149. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  4150. }
  4151. vk_instance.instance = vk::createInstance(instance_create_info);
  4152. vk_instance_initialized = true;
  4153. if (debug_utils_ext) {
  4154. vk_instance.debug_utils_support = true;
  4155. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4156. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4157. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4158. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4159. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4160. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4161. }
  4162. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4163. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4164. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4165. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4166. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4167. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4168. if (devices_env != nullptr) {
  4169. size_t num_available_devices = devices.size();
  4170. std::string devices(devices_env);
  4171. std::replace(devices.begin(), devices.end(), ',', ' ');
  4172. std::stringstream ss(devices);
  4173. size_t tmp;
  4174. while (ss >> tmp) {
  4175. if(tmp >= num_available_devices) {
  4176. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4177. throw std::runtime_error("Invalid Vulkan device index");
  4178. }
  4179. vk_instance.device_indices.push_back(tmp);
  4180. }
  4181. } else {
  4182. // If no vulkan devices are found, return early
  4183. if (devices.empty()) {
  4184. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4185. return;
  4186. }
  4187. // Default to using all dedicated GPUs
  4188. for (size_t i = 0; i < devices.size(); i++) {
  4189. vk::PhysicalDeviceProperties2 new_props;
  4190. vk::PhysicalDeviceDriverProperties new_driver;
  4191. vk::PhysicalDeviceIDProperties new_id;
  4192. new_props.pNext = &new_driver;
  4193. new_driver.pNext = &new_id;
  4194. devices[i].getProperties2(&new_props);
  4195. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4196. // Check if there are two physical devices corresponding to the same GPU
  4197. auto old_device = std::find_if(
  4198. vk_instance.device_indices.begin(),
  4199. vk_instance.device_indices.end(),
  4200. [&devices, &new_id](const size_t k){
  4201. vk::PhysicalDeviceProperties2 old_props;
  4202. vk::PhysicalDeviceIDProperties old_id;
  4203. old_props.pNext = &old_id;
  4204. devices[k].getProperties2(&old_props);
  4205. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4206. equals = equals || (
  4207. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4208. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4209. );
  4210. return equals;
  4211. }
  4212. );
  4213. if (old_device == vk_instance.device_indices.end()) {
  4214. vk_instance.device_indices.push_back(i);
  4215. } else {
  4216. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4217. // This can cause error when splitting layers aross the devices, need to keep only 1
  4218. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4219. vk::PhysicalDeviceProperties2 old_props;
  4220. vk::PhysicalDeviceDriverProperties old_driver;
  4221. old_props.pNext = &old_driver;
  4222. devices[*old_device].getProperties2(&old_props);
  4223. std::map<vk::DriverId, int> driver_priorities {};
  4224. int old_priority = std::numeric_limits<int>::max();
  4225. int new_priority = std::numeric_limits<int>::max();
  4226. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4227. // Smaller number -> higher priority
  4228. switch (old_props.properties.vendorID) {
  4229. case VK_VENDOR_ID_AMD:
  4230. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4231. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4232. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4233. break;
  4234. case VK_VENDOR_ID_INTEL:
  4235. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4236. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4237. break;
  4238. case VK_VENDOR_ID_NVIDIA:
  4239. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4240. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4241. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4242. #endif
  4243. break;
  4244. }
  4245. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4246. if (driver_priorities.count(old_driver.driverID)) {
  4247. old_priority = driver_priorities[old_driver.driverID];
  4248. }
  4249. if (driver_priorities.count(new_driver.driverID)) {
  4250. new_priority = driver_priorities[new_driver.driverID];
  4251. }
  4252. if (new_priority < old_priority) {
  4253. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4254. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4255. vk_instance.device_indices.push_back(i);
  4256. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4257. }
  4258. else {
  4259. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4260. }
  4261. }
  4262. }
  4263. }
  4264. // If no GPUs found, fall back to the first non-CPU device.
  4265. // If only CPU devices are available, return without devices.
  4266. if (vk_instance.device_indices.empty()) {
  4267. for (size_t i = 0; i < devices.size(); i++) {
  4268. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4269. vk_instance.device_indices.push_back(i);
  4270. break;
  4271. }
  4272. }
  4273. }
  4274. if (vk_instance.device_indices.empty()) {
  4275. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4276. return;
  4277. }
  4278. }
  4279. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4280. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4281. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4282. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4283. bool membudget_supported = false;
  4284. for (const auto & ext : extensionprops) {
  4285. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4286. membudget_supported = true;
  4287. break;
  4288. }
  4289. }
  4290. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4291. ggml_vk_print_gpu_info(i);
  4292. }
  4293. }
  4294. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4295. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4296. ggml_vk_instance_init();
  4297. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4298. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4299. ctx->device = ggml_vk_get_device(idx);
  4300. ctx->semaphore_idx = 0;
  4301. ctx->event_idx = 0;
  4302. ctx->prealloc_size_x = 0;
  4303. ctx->prealloc_size_y = 0;
  4304. ctx->prealloc_size_split_k = 0;
  4305. ctx->fence = ctx->device->device.createFence({});
  4306. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4307. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4308. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4309. #ifdef GGML_VULKAN_CHECK_RESULTS
  4310. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4311. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4312. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4313. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4314. #endif
  4315. }
  4316. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4317. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4318. switch (type) {
  4319. case GGML_TYPE_F32:
  4320. case GGML_TYPE_Q4_0:
  4321. case GGML_TYPE_Q4_1:
  4322. case GGML_TYPE_Q5_0:
  4323. case GGML_TYPE_Q5_1:
  4324. case GGML_TYPE_Q8_0:
  4325. case GGML_TYPE_Q2_K:
  4326. case GGML_TYPE_Q3_K:
  4327. case GGML_TYPE_Q4_K:
  4328. case GGML_TYPE_Q5_K:
  4329. case GGML_TYPE_Q6_K:
  4330. case GGML_TYPE_IQ1_S:
  4331. case GGML_TYPE_IQ1_M:
  4332. case GGML_TYPE_IQ2_XXS:
  4333. case GGML_TYPE_IQ2_XS:
  4334. case GGML_TYPE_IQ2_S:
  4335. case GGML_TYPE_IQ3_XXS:
  4336. case GGML_TYPE_IQ3_S:
  4337. case GGML_TYPE_IQ4_XS:
  4338. case GGML_TYPE_IQ4_NL:
  4339. case GGML_TYPE_MXFP4:
  4340. break;
  4341. default:
  4342. return nullptr;
  4343. }
  4344. return ctx->device->pipeline_dequant[type];
  4345. }
  4346. 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) {
  4347. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4348. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4349. return ctx->device->pipeline_matmul_f32;
  4350. }
  4351. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4352. return ctx->device->pipeline_matmul_f32_f16;
  4353. }
  4354. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4355. return ctx->device->pipeline_matmul_bf16;
  4356. }
  4357. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4358. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4359. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4360. }
  4361. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4362. return ctx->device->pipeline_matmul_f16.f16acc;
  4363. }
  4364. } else {
  4365. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4366. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4367. }
  4368. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4369. return ctx->device->pipeline_matmul_f16.f32acc;
  4370. }
  4371. }
  4372. // MMQ
  4373. if (src1_type == GGML_TYPE_Q8_1) {
  4374. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4375. if (pipelines->is_empty()) {
  4376. return nullptr;
  4377. }
  4378. return pipelines;
  4379. }
  4380. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4381. return nullptr;
  4382. }
  4383. switch (src0_type) {
  4384. case GGML_TYPE_Q4_0:
  4385. case GGML_TYPE_Q4_1:
  4386. case GGML_TYPE_Q5_0:
  4387. case GGML_TYPE_Q5_1:
  4388. case GGML_TYPE_Q8_0:
  4389. case GGML_TYPE_Q2_K:
  4390. case GGML_TYPE_Q3_K:
  4391. case GGML_TYPE_Q4_K:
  4392. case GGML_TYPE_Q5_K:
  4393. case GGML_TYPE_Q6_K:
  4394. case GGML_TYPE_IQ1_S:
  4395. case GGML_TYPE_IQ1_M:
  4396. case GGML_TYPE_IQ2_XXS:
  4397. case GGML_TYPE_IQ2_XS:
  4398. case GGML_TYPE_IQ2_S:
  4399. case GGML_TYPE_IQ3_XXS:
  4400. case GGML_TYPE_IQ3_S:
  4401. case GGML_TYPE_IQ4_XS:
  4402. case GGML_TYPE_IQ4_NL:
  4403. case GGML_TYPE_MXFP4:
  4404. break;
  4405. default:
  4406. return nullptr;
  4407. }
  4408. if (ctx->device->coopmat2) {
  4409. assert(src1_type == GGML_TYPE_F16);
  4410. 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;
  4411. }
  4412. if (ctx->device->coopmat_support) {
  4413. 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;
  4414. }
  4415. 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;
  4416. }
  4417. 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) {
  4418. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4419. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4420. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4421. if (b_type == GGML_TYPE_Q8_1) {
  4422. switch (a_type) {
  4423. case GGML_TYPE_Q4_0:
  4424. case GGML_TYPE_Q4_1:
  4425. case GGML_TYPE_Q5_0:
  4426. case GGML_TYPE_Q5_1:
  4427. case GGML_TYPE_Q8_0:
  4428. break;
  4429. default:
  4430. return nullptr;
  4431. }
  4432. }
  4433. switch (a_type) {
  4434. case GGML_TYPE_F32:
  4435. case GGML_TYPE_F16:
  4436. case GGML_TYPE_BF16:
  4437. case GGML_TYPE_Q4_0:
  4438. case GGML_TYPE_Q4_1:
  4439. case GGML_TYPE_Q5_0:
  4440. case GGML_TYPE_Q5_1:
  4441. case GGML_TYPE_Q8_0:
  4442. case GGML_TYPE_Q2_K:
  4443. case GGML_TYPE_Q3_K:
  4444. case GGML_TYPE_Q4_K:
  4445. case GGML_TYPE_Q5_K:
  4446. case GGML_TYPE_Q6_K:
  4447. case GGML_TYPE_IQ1_S:
  4448. case GGML_TYPE_IQ1_M:
  4449. case GGML_TYPE_IQ2_XXS:
  4450. case GGML_TYPE_IQ2_XS:
  4451. case GGML_TYPE_IQ2_S:
  4452. case GGML_TYPE_IQ3_XXS:
  4453. case GGML_TYPE_IQ3_S:
  4454. case GGML_TYPE_IQ4_XS:
  4455. case GGML_TYPE_IQ4_NL:
  4456. case GGML_TYPE_MXFP4:
  4457. break;
  4458. default:
  4459. return nullptr;
  4460. }
  4461. // heuristic to choose workgroup size
  4462. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4463. 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) {
  4464. // Prefer larger workgroups when M is small, to spread the work out more
  4465. // and keep more SMs busy.
  4466. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4467. if (a_type == GGML_TYPE_Q6_K) {
  4468. if (m < 4096 && k >= 1024) {
  4469. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4470. }
  4471. } else {
  4472. if (m <= 8192 && k >= 1024) {
  4473. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4474. }
  4475. }
  4476. }
  4477. if (b_type == GGML_TYPE_Q8_1) {
  4478. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4479. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4480. }
  4481. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4482. }
  4483. 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];
  4484. }
  4485. 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) {
  4486. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4487. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4488. return ctx->device->pipeline_matmul_id_f32;
  4489. }
  4490. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4491. return ctx->device->pipeline_matmul_id_bf16;
  4492. }
  4493. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4494. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4495. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4496. }
  4497. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4498. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4499. }
  4500. } else {
  4501. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4502. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4503. }
  4504. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4505. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4506. }
  4507. }
  4508. // MMQ
  4509. if (src1_type == GGML_TYPE_Q8_1) {
  4510. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4511. if (pipelines->is_empty()) {
  4512. return nullptr;
  4513. }
  4514. return pipelines;
  4515. }
  4516. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4517. switch (src0_type) {
  4518. case GGML_TYPE_Q4_0:
  4519. case GGML_TYPE_Q4_1:
  4520. case GGML_TYPE_Q5_0:
  4521. case GGML_TYPE_Q5_1:
  4522. case GGML_TYPE_Q8_0:
  4523. case GGML_TYPE_Q2_K:
  4524. case GGML_TYPE_Q3_K:
  4525. case GGML_TYPE_Q4_K:
  4526. case GGML_TYPE_Q5_K:
  4527. case GGML_TYPE_Q6_K:
  4528. case GGML_TYPE_IQ1_S:
  4529. case GGML_TYPE_IQ1_M:
  4530. case GGML_TYPE_IQ2_XXS:
  4531. case GGML_TYPE_IQ2_XS:
  4532. case GGML_TYPE_IQ2_S:
  4533. case GGML_TYPE_IQ3_XXS:
  4534. case GGML_TYPE_IQ3_S:
  4535. case GGML_TYPE_IQ4_XS:
  4536. case GGML_TYPE_IQ4_NL:
  4537. case GGML_TYPE_MXFP4:
  4538. break;
  4539. default:
  4540. return nullptr;
  4541. }
  4542. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4543. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4544. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4545. bool support_fp16acc = !mmp.f16acc->is_empty();
  4546. bool support_fp32acc = !mmp.f32acc->is_empty();
  4547. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4548. return mmp.f16acc;
  4549. } else {
  4550. GGML_ASSERT(support_fp32acc);
  4551. return mmp.f32acc;
  4552. }
  4553. }
  4554. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  4555. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4556. GGML_ASSERT(b_type == GGML_TYPE_F32);
  4557. switch (a_type) {
  4558. case GGML_TYPE_F32:
  4559. case GGML_TYPE_F16:
  4560. case GGML_TYPE_BF16:
  4561. case GGML_TYPE_Q4_0:
  4562. case GGML_TYPE_Q4_1:
  4563. case GGML_TYPE_Q5_0:
  4564. case GGML_TYPE_Q5_1:
  4565. case GGML_TYPE_Q8_0:
  4566. case GGML_TYPE_Q2_K:
  4567. case GGML_TYPE_Q3_K:
  4568. case GGML_TYPE_Q4_K:
  4569. case GGML_TYPE_Q5_K:
  4570. case GGML_TYPE_Q6_K:
  4571. case GGML_TYPE_IQ1_S:
  4572. case GGML_TYPE_IQ1_M:
  4573. case GGML_TYPE_IQ2_XXS:
  4574. case GGML_TYPE_IQ2_XS:
  4575. case GGML_TYPE_IQ2_S:
  4576. case GGML_TYPE_IQ3_XXS:
  4577. case GGML_TYPE_IQ3_S:
  4578. case GGML_TYPE_IQ4_XS:
  4579. case GGML_TYPE_IQ4_NL:
  4580. case GGML_TYPE_MXFP4:
  4581. break;
  4582. default:
  4583. return nullptr;
  4584. }
  4585. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  4586. }
  4587. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4588. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4589. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4590. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4591. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4592. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4593. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4594. size/1024.0/1024.0);
  4595. device->device.freeMemory(buf->device_memory);
  4596. device->device.destroyBuffer(buf->buffer);
  4597. return nullptr;
  4598. }
  4599. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4600. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4601. return buf->ptr;
  4602. }
  4603. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4604. if (ptr == nullptr) {
  4605. return;
  4606. }
  4607. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4608. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4609. vk_buffer buf;
  4610. size_t index;
  4611. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4612. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4613. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4614. if (ptr >= addr && ptr < endr) {
  4615. buf = std::get<2>(device->pinned_memory[i]);
  4616. index = i;
  4617. break;
  4618. }
  4619. }
  4620. if (buf == nullptr) {
  4621. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4622. return;
  4623. }
  4624. ggml_vk_destroy_buffer(buf);
  4625. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4626. }
  4627. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4628. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4629. buf = nullptr;
  4630. buf_offset = 0;
  4631. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4632. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4633. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4634. if (ptr >= addr && ptr < endr) {
  4635. buf = std::get<2>(device->pinned_memory[i]);
  4636. buf_offset = ((const uint8_t *)ptr) - addr;
  4637. break;
  4638. }
  4639. }
  4640. }
  4641. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  4642. vk_submission s;
  4643. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  4644. if (one_time) {
  4645. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  4646. } else {
  4647. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  4648. }
  4649. return s;
  4650. }
  4651. template <typename T> size_t push_constant_size(const T &t) {
  4652. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4653. GGML_UNUSED(t);
  4654. return sizeof(T);
  4655. }
  4656. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4657. GGML_UNUSED(t);
  4658. return sizeof(T) * t.size();
  4659. }
  4660. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4661. GGML_UNUSED(t);
  4662. return sizeof(T) * N;
  4663. }
  4664. template <typename T> const T *push_constant_data(const T &t) {
  4665. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4666. return &t;
  4667. }
  4668. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4669. return t.data();
  4670. }
  4671. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4672. return t.data();
  4673. }
  4674. template <typename T>
  4675. 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) {
  4676. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4677. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4678. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4679. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4680. for (auto& buffer : descriptor_buffer_infos) {
  4681. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4682. }
  4683. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4684. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4685. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4686. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4687. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4688. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4689. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4690. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4691. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4692. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4693. pipeline->layout,
  4694. 0,
  4695. { descriptor_set },
  4696. {});
  4697. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4698. }
  4699. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4700. s.buffer.end();
  4701. s.wait_semaphores = std::move(wait_semaphores);
  4702. s.signal_semaphores = std::move(signal_semaphores);
  4703. }
  4704. static void ggml_vk_ctx_end(vk_context& ctx) {
  4705. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4706. if (ctx->s == nullptr) {
  4707. return;
  4708. }
  4709. ctx->s->buffer.end();
  4710. ctx->s = nullptr;
  4711. }
  4712. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4713. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4714. if (subctx->s != nullptr) {
  4715. ggml_vk_ctx_end(subctx);
  4716. }
  4717. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4718. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4719. }
  4720. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4721. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4722. return CEIL_DIV(width, align) * align;
  4723. }
  4724. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4725. if (memcpys == nullptr) {
  4726. memcpy(dst, src, size);
  4727. } else {
  4728. memcpys->emplace_back(dst, src, size);
  4729. }
  4730. }
  4731. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  4732. if (memsets == nullptr) {
  4733. memset(dst, val, size);
  4734. } else {
  4735. memsets->emplace_back(dst, val, size);
  4736. }
  4737. }
  4738. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4739. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4740. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4741. ggml_vk_destroy_buffer(device->sync_staging);
  4742. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4743. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4744. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4745. }
  4746. }
  4747. 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) {
  4748. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4749. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4750. // Buffer is already mapped
  4751. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4752. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4753. GGML_ABORT("fatal error");
  4754. }
  4755. // Check if src is pinned memory
  4756. vk_buffer buf = nullptr;
  4757. size_t buf_offset = 0;
  4758. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4759. const uint64_t ne0 = tensor->ne[0];
  4760. const uint64_t ne1 = tensor->ne[1];
  4761. const uint64_t ne2 = tensor->ne[2];
  4762. const uint64_t ne3 = tensor->ne[3];
  4763. const uint64_t nb0 = tensor->nb[0];
  4764. const uint64_t nb1 = tensor->nb[1];
  4765. const uint64_t nb2 = tensor->nb[2];
  4766. const uint64_t nb3 = tensor->nb[3];
  4767. const ggml_type type = tensor->type;
  4768. const uint64_t ts = ggml_type_size(type);
  4769. const uint64_t bs = ggml_blck_size(type);
  4770. const uint64_t dstnb0 = ts;
  4771. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4772. const uint64_t dstnb2 = dstnb1*ne1;
  4773. const uint64_t dstnb3 = dstnb2*ne2;
  4774. const uint64_t ne = ggml_nelements(tensor);
  4775. if (buf != nullptr) {
  4776. // Memory is pinned, use as staging buffer
  4777. std::vector<vk::BufferCopy> slices;
  4778. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4779. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4780. // Find longest contiguous slice
  4781. if (ne1*nb1 == dstnb2) {
  4782. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4783. } else {
  4784. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4785. if (ne0*nb0/bs == dstnb1) {
  4786. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4787. } else {
  4788. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4789. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4790. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4791. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4792. }
  4793. }
  4794. }
  4795. }
  4796. }
  4797. }
  4798. ggml_vk_sync_buffers(ctx, subctx);
  4799. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4800. return;
  4801. }
  4802. if (!sync_staging) {
  4803. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4804. }
  4805. // Staging buffer required
  4806. vk_buffer& staging = ctx->device->sync_staging;
  4807. const uint64_t copy_size = ts*ne/bs;
  4808. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  4809. VkBufferCopy buf_copy{ 0, offset, copy_size };
  4810. ggml_vk_sync_buffers(ctx, subctx);
  4811. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4812. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4813. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4814. // Find longest contiguous slice
  4815. if (ne1*nb1 == dstnb2) {
  4816. 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);
  4817. } else {
  4818. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4819. if (ne0*nb0/bs == dstnb1) {
  4820. 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);
  4821. } else {
  4822. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4823. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4824. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4825. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  4826. }
  4827. }
  4828. }
  4829. }
  4830. }
  4831. }
  4832. }
  4833. static void ggml_vk_buffer_write_2d_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height, bool sync_staging = false) {
  4834. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  4835. // Buffer is already mapped
  4836. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4837. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4838. GGML_ABORT("fatal error");
  4839. }
  4840. // Check if src is pinned memory
  4841. vk_buffer buf = nullptr;
  4842. size_t buf_offset = 0;
  4843. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  4844. if (buf != nullptr) {
  4845. // Memory is pinned, use as staging buffer
  4846. std::vector<vk::BufferCopy> slices(1);
  4847. if (width == spitch) {
  4848. // Only do single write if stride is equal
  4849. slices[0].srcOffset = buf_offset;
  4850. slices[0].dstOffset = offset;
  4851. slices[0].size = width * height;
  4852. } else {
  4853. slices.resize(height);
  4854. for (size_t i = 0; i < height; i++) {
  4855. slices[i].srcOffset = buf_offset + i * spitch;
  4856. slices[i].dstOffset = offset + i * width;
  4857. slices[i].size = width;
  4858. }
  4859. }
  4860. ggml_vk_sync_buffers(nullptr, subctx);
  4861. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4862. return;
  4863. }
  4864. VK_LOG_DEBUG("STAGING");
  4865. if (!sync_staging) {
  4866. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4867. }
  4868. // Staging buffer required
  4869. const size_t copy_size = width*height;
  4870. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  4871. vk_buffer& staging_buffer = dst->device->sync_staging;
  4872. VkBufferCopy buf_copy = {
  4873. 0,
  4874. offset,
  4875. copy_size};
  4876. ggml_vk_sync_buffers(nullptr, subctx);
  4877. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4878. if (width == spitch) {
  4879. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  4880. } else {
  4881. for (size_t i = 0; i < height; i++) {
  4882. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  4883. }
  4884. }
  4885. }
  4886. static void ggml_vk_buffer_write_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  4887. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  4888. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  4889. }
  4890. 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) {
  4891. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  4892. // Buffer is already mapped
  4893. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4894. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4895. for (size_t i = 0; i < height; i++) {
  4896. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  4897. }
  4898. } else {
  4899. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4900. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4901. ggml_vk_ctx_begin(dst->device, subctx);
  4902. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  4903. ggml_vk_ctx_end(subctx);
  4904. for (auto& cpy : subctx->in_memcpys) {
  4905. memcpy(cpy.dst, cpy.src, cpy.n);
  4906. }
  4907. for (auto& mset : subctx->memsets) {
  4908. memset(mset.dst, mset.val, mset.n);
  4909. }
  4910. ggml_vk_submit(subctx, dst->device->fence);
  4911. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  4912. dst->device->device.resetFences({ dst->device->fence });
  4913. ggml_vk_queue_command_pools_cleanup(dst->device);
  4914. }
  4915. }
  4916. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  4917. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  4918. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  4919. }
  4920. static void ggml_vk_buffer_read_2d_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t spitch, size_t dpitch, size_t width, size_t height, bool sync_staging = false) {
  4921. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  4922. GGML_ASSERT(width > 0);
  4923. GGML_ASSERT(height > 0);
  4924. GGML_ASSERT(src != nullptr);
  4925. // TODO: staging_offset is not used
  4926. // Check if dst is pinned memory
  4927. vk_buffer buf = nullptr;
  4928. size_t buf_offset = 0;
  4929. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  4930. std::vector<vk::BufferCopy> slices(1);
  4931. if (width == spitch && width == dpitch) {
  4932. // Only do single write if stride is equal
  4933. slices[0].srcOffset = offset;
  4934. slices[0].dstOffset = buf_offset;
  4935. slices[0].size = width * height;
  4936. } else {
  4937. slices.resize(height);
  4938. for (size_t i = 0; i < height; i++) {
  4939. slices[i].srcOffset = offset + i * spitch;
  4940. slices[i].dstOffset = buf_offset + i * dpitch;
  4941. slices[i].size = width;
  4942. }
  4943. }
  4944. if (buf != nullptr) {
  4945. // Memory is pinned, use as staging buffer
  4946. ggml_vk_sync_buffers(nullptr, subctx);
  4947. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  4948. return;
  4949. }
  4950. VK_LOG_DEBUG("STAGING");
  4951. if (!sync_staging) {
  4952. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  4953. }
  4954. // Fall back to staging buffer
  4955. const size_t copy_size = dpitch * height;
  4956. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  4957. vk_buffer& staging_buffer = src->device->sync_staging;
  4958. ggml_vk_sync_buffers(nullptr, subctx);
  4959. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  4960. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  4961. }
  4962. static void ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  4963. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  4964. }
  4965. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  4966. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  4967. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  4968. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  4969. // the HW device to host copy path.
  4970. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  4971. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4972. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  4973. } else {
  4974. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4975. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4976. ggml_vk_ctx_begin(src->device, subctx);
  4977. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  4978. ggml_vk_ctx_end(subctx);
  4979. ggml_vk_submit(subctx, src->device->fence);
  4980. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  4981. src->device->device.resetFences({ src->device->fence });
  4982. ggml_vk_queue_command_pools_cleanup(src->device);
  4983. for (auto& cpy : subctx->out_memcpys) {
  4984. memcpy(cpy.dst, cpy.src, cpy.n);
  4985. }
  4986. }
  4987. }
  4988. 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) {
  4989. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  4990. // Make sure both buffers are on same device
  4991. GGML_ASSERT(src->device == dst->device);
  4992. VkBufferCopy bc{ src_offset, dst_offset, size };
  4993. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  4994. }
  4995. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  4996. if (src->device == dst->device) {
  4997. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4998. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  4999. // Copy within the device
  5000. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5001. ggml_vk_ctx_begin(src->device, subctx);
  5002. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5003. ggml_vk_ctx_end(subctx);
  5004. ggml_vk_submit(subctx, src->device->fence);
  5005. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5006. src->device->device.resetFences({ src->device->fence });
  5007. ggml_vk_queue_command_pools_cleanup(src->device);
  5008. } else {
  5009. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5010. // Copy device to device
  5011. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5012. // Copy to src staging buffer
  5013. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5014. // Copy to dst buffer
  5015. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5016. }
  5017. }
  5018. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5019. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5020. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5021. dst->device->uma) {
  5022. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5023. return;
  5024. }
  5025. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5026. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5027. }
  5028. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5029. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5030. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5031. dst->device->uma) {
  5032. memset((uint8_t*)dst->ptr + offset, c, size);
  5033. return;
  5034. }
  5035. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5036. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5037. ggml_vk_ctx_begin(dst->device, subctx);
  5038. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5039. ggml_vk_ctx_end(subctx);
  5040. ggml_vk_submit(subctx, dst->device->fence);
  5041. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5042. dst->device->device.resetFences({ dst->device->fence });
  5043. ggml_vk_queue_command_pools_cleanup(dst->device);
  5044. }
  5045. 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) {
  5046. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5047. if (disable_split_k) {
  5048. return 1;
  5049. }
  5050. uint32_t split_k = 1;
  5051. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5052. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5053. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5054. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5055. if (k >= 2048) {
  5056. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5057. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5058. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5059. split_k = 3;
  5060. }
  5061. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5062. split_k = std::min(split_k, 8u);
  5063. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5064. // If this rounded up size would cause the last split to be empty,
  5065. // then reduce the split count.
  5066. while (true) {
  5067. if (split_k == 1) {
  5068. break;
  5069. }
  5070. uint32_t k_split = CEIL_DIV(k, split_k);
  5071. k_split = ROUNDUP_POW2(k_split, 256);
  5072. if (k_split * (split_k - 1) < k) {
  5073. break;
  5074. }
  5075. split_k--;
  5076. }
  5077. }
  5078. }
  5079. return split_k;
  5080. }
  5081. 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) {
  5082. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5083. if (ctx->device->coopmat2) {
  5084. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5085. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5086. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5087. // Use large shader when the N dimension is greater than the medium shader's tile size
  5088. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5089. // Prefer large over medium if either:
  5090. // - medium or large tiles would overfill the GPU
  5091. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5092. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5093. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5094. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5095. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5096. 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])) {
  5097. return aligned ? mmp->a_l : mmp->l;
  5098. }
  5099. // Use medium shader when the N dimension is greater than the small shader's tile size
  5100. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5101. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5102. return aligned ? mmp->a_m : mmp->m;
  5103. }
  5104. return aligned ? mmp->a_s : mmp->s;
  5105. }
  5106. 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])) {
  5107. return aligned ? mmp->a_s : mmp->s;
  5108. }
  5109. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5110. return aligned ? mmp->a_m : mmp->m;
  5111. }
  5112. return aligned ? mmp->a_l : mmp->l;
  5113. GGML_UNUSED(src1_type);
  5114. }
  5115. 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) {
  5116. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5117. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5118. }
  5119. static void ggml_vk_matmul(
  5120. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5121. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5122. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5123. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5124. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5125. uint32_t padded_n) {
  5126. 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 << ")");
  5127. if (split_k == 1) {
  5128. 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 };
  5129. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5130. return;
  5131. }
  5132. if (ctx->prealloc_split_k_need_sync) {
  5133. ggml_vk_sync_buffers(ctx, subctx);
  5134. }
  5135. GGML_ASSERT(batch_stride_d == m * n);
  5136. // Round the split size up to a multiple of 256 (k-quant alignment)
  5137. uint32_t k_split = CEIL_DIV(k, split_k);
  5138. k_split = ROUNDUP_POW2(k_split, 256);
  5139. 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 };
  5140. // Make sure enough workgroups get assigned for split k to work
  5141. 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 });
  5142. ggml_vk_sync_buffers(ctx, subctx);
  5143. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5144. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5145. ctx->prealloc_split_k_need_sync = true;
  5146. }
  5147. 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) {
  5148. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5149. if (ctx->device->coopmat2) {
  5150. // Use large shader when the N dimension is greater than the medium shader's tile size
  5151. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5152. 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])) {
  5153. return aligned ? mmp->a_l : mmp->l;
  5154. }
  5155. // Use medium shader when the N dimension is greater than the small shader's tile size
  5156. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5157. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5158. return aligned ? mmp->a_m : mmp->m;
  5159. }
  5160. return aligned ? mmp->a_s : mmp->s;
  5161. }
  5162. 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])) {
  5163. return aligned ? mmp->a_s : mmp->s;
  5164. }
  5165. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5166. return aligned ? mmp->a_m : mmp->m;
  5167. }
  5168. return aligned ? mmp->a_l : mmp->l;
  5169. }
  5170. 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) {
  5171. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5172. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5173. }
  5174. static void ggml_vk_matmul_id(
  5175. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5176. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5177. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5178. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5179. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5180. uint32_t padded_n) {
  5181. 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 << "), " <<
  5182. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5183. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5184. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5185. 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,
  5186. nei0, nei1, nbi1, ne11, padded_n };
  5187. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5188. }
  5189. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5190. return
  5191. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5192. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5193. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5194. }
  5195. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5196. // Choose "contiguous copy" shader if src/dst are contiguous
  5197. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5198. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5199. if (contig) {
  5200. return ctx->device->pipeline_contig_cpy_f32_f32;
  5201. } else {
  5202. return ctx->device->pipeline_cpy_f32_f32;
  5203. }
  5204. }
  5205. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5206. if (contig) {
  5207. return ctx->device->pipeline_contig_cpy_f32_f16;
  5208. } else {
  5209. return ctx->device->pipeline_cpy_f32_f16;
  5210. }
  5211. }
  5212. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5213. if (contig) {
  5214. return ctx->device->pipeline_contig_cpy_f16_f16;
  5215. } else {
  5216. return ctx->device->pipeline_cpy_f16_f16;
  5217. }
  5218. }
  5219. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5220. if (contig) {
  5221. return ctx->device->pipeline_contig_cpy_f16_f32;
  5222. } else {
  5223. return ctx->device->pipeline_cpy_f16_f32;
  5224. }
  5225. }
  5226. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5227. if (contig) {
  5228. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5229. } else {
  5230. return ctx->device->pipeline_cpy_f32_bf16;
  5231. }
  5232. }
  5233. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5234. if (contig) {
  5235. return ctx->device->pipeline_contig_cpy_f32_i32;
  5236. } else {
  5237. return ctx->device->pipeline_cpy_f32_i32;
  5238. }
  5239. }
  5240. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5241. if (contig) {
  5242. return ctx->device->pipeline_contig_cpy_i32_f32;
  5243. } else {
  5244. return ctx->device->pipeline_cpy_i32_f32;
  5245. }
  5246. }
  5247. if (src->type == GGML_TYPE_F32) {
  5248. switch (to) {
  5249. case GGML_TYPE_Q4_0:
  5250. case GGML_TYPE_Q4_1:
  5251. case GGML_TYPE_Q5_0:
  5252. case GGML_TYPE_Q5_1:
  5253. case GGML_TYPE_Q8_0:
  5254. case GGML_TYPE_IQ4_NL:
  5255. return ctx->device->pipeline_cpy_f32_quant[to];
  5256. default:
  5257. break;
  5258. }
  5259. }
  5260. if (to == GGML_TYPE_F32) {
  5261. switch (src->type) {
  5262. case GGML_TYPE_Q4_0:
  5263. case GGML_TYPE_Q4_1:
  5264. case GGML_TYPE_Q5_0:
  5265. case GGML_TYPE_Q5_1:
  5266. case GGML_TYPE_Q8_0:
  5267. case GGML_TYPE_IQ4_NL:
  5268. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5269. default:
  5270. break;
  5271. }
  5272. }
  5273. if (src->type == to) {
  5274. // Copy two or four bytes at a time, depending on block size.
  5275. // For quantized types, we scale by block size/type size. But
  5276. // this path is also used for bf16->bf16 for example, where the
  5277. // type size must be exactly 2 or 4.
  5278. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5279. if ((ggml_type_size(src->type) % 4) == 0) {
  5280. if (contig) {
  5281. return ctx->device->pipeline_contig_cpy_f32_f32;
  5282. } else {
  5283. return ctx->device->pipeline_cpy_f32_f32;
  5284. }
  5285. } else {
  5286. if (contig) {
  5287. return ctx->device->pipeline_contig_cpy_f16_f16;
  5288. } else {
  5289. return ctx->device->pipeline_cpy_f16_f16;
  5290. }
  5291. }
  5292. }
  5293. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5294. GGML_ABORT("fatal error");
  5295. }
  5296. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, vk_subbuffer&& in, vk_subbuffer&& out) {
  5297. 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] << "), ";
  5298. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5299. const int tensor_type_size = ggml_type_size(tensor->type);
  5300. const uint32_t ne = ggml_nelements(tensor);
  5301. std::array<uint32_t, 3> elements;
  5302. if (ne > 262144) {
  5303. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5304. } else if (ne > 512) {
  5305. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5306. } else {
  5307. elements = { ne, 1, 1 };
  5308. }
  5309. vk_op_unary_push_constants pc = {
  5310. (uint32_t)ne,
  5311. (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,
  5312. (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]),
  5313. 0,
  5314. 0.0f, 0.0f,
  5315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5316. };
  5317. init_pushconst_fastdiv(pc);
  5318. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5319. ggml_vk_sync_buffers(ctx, subctx);
  5320. }
  5321. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type, bool use_x4_blocks) {
  5322. switch(type) {
  5323. case GGML_TYPE_Q8_1:
  5324. return use_x4_blocks ? ctx->device->pipeline_quantize_q8_1_x4 : ctx->device->pipeline_quantize_q8_1;
  5325. default:
  5326. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5327. GGML_ABORT("fatal error");
  5328. }
  5329. }
  5330. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, vk_subbuffer&& in, vk_subbuffer&& out, uint32_t ne, bool use_x4_blocks = false) {
  5331. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5332. vk_pipeline pipeline = use_x4_blocks ? ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true) : ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, false);
  5333. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5334. ggml_vk_sync_buffers(ctx, subctx);
  5335. }
  5336. 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, bool dryrun = false) {
  5337. 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];
  5338. 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];
  5339. 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];
  5340. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5341. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5342. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5343. const uint64_t ne00 = src0->ne[0];
  5344. const uint64_t ne01 = src0->ne[1];
  5345. const uint64_t ne02 = src0->ne[2];
  5346. const uint64_t ne03 = src0->ne[3];
  5347. const uint64_t ne10 = src1->ne[0];
  5348. const uint64_t ne11 = src1->ne[1];
  5349. const uint64_t ne12 = src1->ne[2];
  5350. const uint64_t ne13 = src1->ne[3];
  5351. const uint64_t ne21 = dst->ne[1];
  5352. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5353. const uint32_t stride_batch_d = stride_d*ne21;
  5354. const uint64_t r2 = ne12 / ne02;
  5355. const uint64_t r3 = ne13 / ne03;
  5356. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5357. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5358. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5359. vk_buffer d_Qx = nullptr;
  5360. size_t qx_buf_offset = 0;
  5361. vk_buffer d_Qy = nullptr;
  5362. size_t qy_buf_offset = 0;
  5363. bool src0_uma = false;
  5364. bool src1_uma = false;
  5365. if (ctx->device->uma) {
  5366. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5367. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5368. src0_uma = d_Qx != nullptr;
  5369. src1_uma = d_Qy != nullptr;
  5370. }
  5371. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5372. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5373. !ggml_vk_dim01_contiguous(src0);
  5374. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5375. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5376. !ggml_vk_dim01_contiguous(src1);
  5377. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5378. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5379. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5380. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  5381. // Check for mmq first
  5382. 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;
  5383. if (mmp == nullptr) {
  5384. // Fall back to f16 dequant mul mat
  5385. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5386. quantize_y = false;
  5387. }
  5388. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5389. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5390. if (qx_needs_dequant) {
  5391. // Fall back to dequant + f16 mulmat
  5392. 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]);
  5393. }
  5394. // Not implemented
  5395. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5396. 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)));
  5397. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5398. 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));
  5399. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5400. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5401. const int x_ne = ne01 * ne00;
  5402. const int y_ne = padded_n * ne10;
  5403. const int d_ne = ne11 * ne01;
  5404. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5405. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5406. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5407. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5408. const uint64_t y_sz = quantize_y ? (y_ne * 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);
  5409. const uint64_t d_sz = sizeof(float) * d_ne;
  5410. vk_pipeline to_fp16_vk_0 = nullptr;
  5411. vk_pipeline to_fp16_vk_1 = nullptr;
  5412. vk_pipeline to_q8_1 = nullptr;
  5413. if (x_non_contig) {
  5414. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5415. } else {
  5416. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5417. }
  5418. if (y_non_contig) {
  5419. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5420. } else {
  5421. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5422. }
  5423. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5424. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5425. if (quantize_y) {
  5426. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5427. }
  5428. if (dryrun) {
  5429. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5430. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5431. if (quantize_y) {
  5432. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5433. }
  5434. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  5435. if (
  5436. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5437. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5438. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5439. GGML_ABORT("Requested preallocation size is too large");
  5440. }
  5441. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5442. ctx->prealloc_size_x = x_sz_upd;
  5443. }
  5444. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5445. ctx->prealloc_size_y = y_sz_upd;
  5446. }
  5447. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5448. ctx->prealloc_size_split_k = split_k_size;
  5449. }
  5450. // Request descriptor sets
  5451. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5452. if (qx_needs_dequant) {
  5453. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5454. }
  5455. if (qy_needs_dequant) {
  5456. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5457. }
  5458. if (quantize_y) {
  5459. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5460. }
  5461. if (split_k > 1) {
  5462. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5463. }
  5464. return;
  5465. }
  5466. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5467. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5468. GGML_ASSERT(d_D != nullptr);
  5469. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  5470. vk_buffer d_X;
  5471. uint64_t x_buf_offset = 0;
  5472. vk_buffer d_Y;
  5473. uint64_t y_buf_offset = 0;
  5474. if (!src0_uma) {
  5475. d_Qx = src0_buf_ctx->dev_buffer;
  5476. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5477. GGML_ASSERT(d_Qx != nullptr);
  5478. }
  5479. if (!src1_uma) {
  5480. d_Qy = src1_buf_ctx->dev_buffer;
  5481. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5482. GGML_ASSERT(d_Qy != nullptr);
  5483. }
  5484. if (qx_needs_dequant) {
  5485. d_X = ctx->prealloc_x;
  5486. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  5487. } else {
  5488. d_X = d_Qx;
  5489. x_buf_offset = qx_buf_offset;
  5490. GGML_ASSERT(qx_sz == x_sz);
  5491. }
  5492. if (qy_needs_dequant) {
  5493. d_Y = ctx->prealloc_y;
  5494. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  5495. } else if (quantize_y) {
  5496. d_Y = ctx->prealloc_y;
  5497. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5498. } else {
  5499. d_Y = d_Qy;
  5500. y_buf_offset = qy_buf_offset;
  5501. GGML_ASSERT(qy_sz == y_sz);
  5502. }
  5503. if (x_non_contig || qx_needs_dequant) {
  5504. if (ctx->prealloc_x_need_sync) {
  5505. ggml_vk_sync_buffers(ctx, subctx);
  5506. }
  5507. }
  5508. if (x_non_contig) {
  5509. 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));
  5510. } else if (qx_needs_dequant) {
  5511. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5512. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc, { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  5513. ggml_vk_sync_buffers(ctx, subctx);
  5514. }
  5515. if (y_non_contig) {
  5516. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5517. ctx->prealloc_y_last_tensor_used != src1) {
  5518. if (ctx->prealloc_y_need_sync) {
  5519. ggml_vk_sync_buffers(ctx, subctx);
  5520. }
  5521. 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));
  5522. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5523. ctx->prealloc_y_last_tensor_used = src1;
  5524. }
  5525. }
  5526. if (quantize_y) {
  5527. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5528. ctx->prealloc_y_last_tensor_used != src1) {
  5529. if (ctx->prealloc_y_need_sync) {
  5530. ggml_vk_sync_buffers(ctx, subctx);
  5531. }
  5532. 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 * ne12 * ne13, true);
  5533. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5534. ctx->prealloc_y_last_tensor_used = src1;
  5535. }
  5536. }
  5537. uint32_t stride_batch_x = ne00*ne01;
  5538. uint32_t stride_batch_y = ne10*ne11;
  5539. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5540. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5541. }
  5542. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5543. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5544. }
  5545. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5546. if (quantize_y) {
  5547. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5548. }
  5549. // compute
  5550. ggml_vk_matmul(
  5551. ctx, subctx, pipeline,
  5552. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz_total },
  5553. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  5554. ne01, ne11, ne10,
  5555. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5556. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5557. ); // NOLINT
  5558. if (x_non_contig || qx_needs_dequant) {
  5559. ctx->prealloc_x_need_sync = true;
  5560. }
  5561. if (y_non_contig || quantize_y) {
  5562. ctx->prealloc_y_need_sync = true;
  5563. }
  5564. }
  5565. // Device tuning
  5566. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5567. if (device->mmvq_mode == 1) {
  5568. return true;
  5569. } else if (device->mmvq_mode == -1) {
  5570. return false;
  5571. }
  5572. // MMVQ is generally good for batches
  5573. if (n > 1) {
  5574. return true;
  5575. }
  5576. switch (device->vendor_id) {
  5577. case VK_VENDOR_ID_NVIDIA:
  5578. switch (src0_type) {
  5579. case GGML_TYPE_Q8_0:
  5580. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5581. default:
  5582. return true;
  5583. }
  5584. case VK_VENDOR_ID_AMD:
  5585. switch (src0_type) {
  5586. case GGML_TYPE_Q8_0:
  5587. return device->architecture == vk_device_architecture::AMD_GCN;
  5588. default:
  5589. return true;
  5590. }
  5591. case VK_VENDOR_ID_INTEL:
  5592. switch (src0_type) {
  5593. // From tests on A770 Linux, may need more tuning
  5594. case GGML_TYPE_Q4_0:
  5595. case GGML_TYPE_Q5_1:
  5596. return false;
  5597. default:
  5598. return true;
  5599. }
  5600. default:
  5601. return true;
  5602. }
  5603. GGML_UNUSED(m);
  5604. GGML_UNUSED(k);
  5605. }
  5606. 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, bool dryrun = false) {
  5607. ggml_tensor * dst = cgraph->nodes[node_idx];
  5608. const ggml_tensor * src0 = dst->src[0];
  5609. const ggml_tensor * src1 = dst->src[1];
  5610. 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];
  5611. 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];
  5612. 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];
  5613. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  5614. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5615. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5616. const uint64_t ne00 = src0->ne[0];
  5617. const uint64_t ne01 = src0->ne[1];
  5618. const uint64_t ne02 = src0->ne[2];
  5619. const uint64_t ne03 = src0->ne[3];
  5620. const uint64_t ne10 = src1->ne[0];
  5621. const uint64_t ne11 = src1->ne[1];
  5622. const uint64_t ne12 = src1->ne[2];
  5623. const uint64_t ne13 = src1->ne[3];
  5624. const uint64_t ne20 = dst->ne[0];
  5625. const uint64_t ne21 = dst->ne[1];
  5626. const uint64_t ne22 = dst->ne[2];
  5627. const uint64_t ne23 = dst->ne[3];
  5628. const uint64_t r2 = ne12 / ne02;
  5629. const uint64_t r3 = ne13 / ne03;
  5630. // batch_n indicates that we need to compute a few vector results, and this assumes
  5631. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  5632. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  5633. bool batch_n = ne11 > 1;
  5634. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5635. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5636. vk_buffer d_Qx = nullptr;
  5637. size_t qx_buf_offset = 0;
  5638. vk_buffer d_Qy = nullptr;
  5639. size_t qy_buf_offset = 0;
  5640. bool src0_uma = false;
  5641. bool src1_uma = false;
  5642. if (ctx->device->uma) {
  5643. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5644. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5645. src0_uma = d_Qx != nullptr;
  5646. src1_uma = d_Qy != nullptr;
  5647. }
  5648. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5649. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5650. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5651. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  5652. vk_pipeline to_fp16_vk_0 = nullptr;
  5653. vk_pipeline to_fp16_vk_1 = nullptr;
  5654. if (x_non_contig) {
  5655. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5656. }
  5657. if (y_non_contig) {
  5658. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5659. } else {
  5660. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5661. }
  5662. // Check for mmq first
  5663. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  5664. vk_pipeline to_q8_1 = nullptr;
  5665. if (dmmv == nullptr) {
  5666. // Fall back to f16 dequant mul mat
  5667. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  5668. quantize_y = false;
  5669. }
  5670. if (quantize_y) {
  5671. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5672. }
  5673. const bool qx_needs_dequant = x_non_contig;
  5674. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  5675. // Not implemented
  5676. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5677. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5678. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5679. GGML_ASSERT(dmmv != nullptr);
  5680. const uint64_t x_ne = ne01 * ne00;
  5681. const uint64_t y_ne = ne11 * ne10;
  5682. const uint64_t d_ne = ne11 * ne01;
  5683. 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);
  5684. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5685. 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;
  5686. const uint64_t y_sz = quantize_y ? (y_ne * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5687. const uint64_t d_sz = sizeof(float) * d_ne;
  5688. if (dryrun) {
  5689. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5690. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5691. if (quantize_y) {
  5692. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5693. }
  5694. if (
  5695. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5696. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  5697. GGML_ABORT("Requested preallocation size is too large");
  5698. }
  5699. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5700. ctx->prealloc_size_x = x_sz_upd;
  5701. }
  5702. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5703. ctx->prealloc_size_y = y_sz_upd;
  5704. }
  5705. // Request descriptor sets
  5706. if (qx_needs_dequant) {
  5707. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5708. }
  5709. if (qy_needs_dequant) {
  5710. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5711. }
  5712. if (quantize_y) {
  5713. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5714. }
  5715. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5716. return;
  5717. }
  5718. vk_buffer d_D;
  5719. uint64_t d_buf_offset = 0;
  5720. if (ctx->num_additional_fused_ops > 0) {
  5721. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5722. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  5723. d_D = dst_buf_ctx->dev_buffer;
  5724. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  5725. } else {
  5726. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5727. d_D = dst_buf_ctx->dev_buffer;
  5728. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5729. }
  5730. GGML_ASSERT(d_D != nullptr);
  5731. vk_buffer d_X;
  5732. uint64_t x_buf_offset = 0;
  5733. vk_buffer d_Y;
  5734. uint64_t y_buf_offset = 0;
  5735. if(!src0_uma) {
  5736. d_Qx = src0_buf_ctx->dev_buffer;
  5737. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5738. GGML_ASSERT(d_Qx != nullptr);
  5739. }
  5740. if(!src1_uma) {
  5741. d_Qy = src1_buf_ctx->dev_buffer;
  5742. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5743. GGML_ASSERT(d_Qy != nullptr);
  5744. }
  5745. if (qx_needs_dequant) {
  5746. d_X = ctx->prealloc_x;
  5747. } else {
  5748. d_X = d_Qx;
  5749. x_buf_offset = qx_buf_offset;
  5750. GGML_ASSERT(qx_sz == x_sz);
  5751. }
  5752. if (qy_needs_dequant) {
  5753. d_Y = ctx->prealloc_y;
  5754. } else if (quantize_y) {
  5755. d_Y = ctx->prealloc_y;
  5756. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5757. } else {
  5758. d_Y = d_Qy;
  5759. y_buf_offset = qy_buf_offset;
  5760. GGML_ASSERT(qy_sz == y_sz);
  5761. }
  5762. if (x_non_contig) {
  5763. if (ctx->prealloc_x_need_sync) {
  5764. ggml_vk_sync_buffers(ctx, subctx);
  5765. }
  5766. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5767. 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));
  5768. }
  5769. if (y_non_contig) {
  5770. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5771. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5772. ctx->prealloc_y_last_tensor_used != src1) {
  5773. if (ctx->prealloc_y_need_sync) {
  5774. ggml_vk_sync_buffers(ctx, subctx);
  5775. }
  5776. 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));
  5777. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5778. ctx->prealloc_y_last_tensor_used = src1;
  5779. }
  5780. }
  5781. if (quantize_y) {
  5782. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5783. ctx->prealloc_y_last_tensor_used != src1) {
  5784. if (ctx->prealloc_y_need_sync) {
  5785. ggml_vk_sync_buffers(ctx, subctx);
  5786. }
  5787. 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 * ne12 * ne13, true);
  5788. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5789. ctx->prealloc_y_last_tensor_used = src1;
  5790. }
  5791. }
  5792. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  5793. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  5794. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  5795. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  5796. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5797. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5798. }
  5799. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5800. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5801. }
  5802. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5803. uint32_t groups_x = ne01;
  5804. uint32_t groups_z = 1;
  5805. if (ne01 > max_groups_x) {
  5806. groups_z = 64;
  5807. groups_x = CEIL_DIV(groups_x, groups_z);
  5808. }
  5809. // TODO: Clean up this whole sz * ne_2 * ne_3 thing, it hasn't been necessary for a long time
  5810. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5811. if (quantize_y) {
  5812. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5813. }
  5814. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  5815. vk_buffer d_B = d_D;
  5816. size_t b_buf_offset = 0;
  5817. uint64_t b_sz = 0;
  5818. if (enable_bias) {
  5819. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5820. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5821. bool b_uma = false;
  5822. if (ctx->device->uma) {
  5823. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  5824. b_uma = d_B != nullptr;
  5825. }
  5826. if(!b_uma) {
  5827. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  5828. d_B = bias_buf_ctx->dev_buffer;
  5829. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  5830. GGML_ASSERT(d_B != nullptr);
  5831. b_sz = ggml_nbytes(bias);
  5832. }
  5833. }
  5834. // compute
  5835. const vk_mat_vec_push_constants pc = {
  5836. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5837. stride_batch_x, stride_batch_y, stride_batch_d, enable_bias,
  5838. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  5839. };
  5840. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5841. {
  5842. vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  5843. vk_subbuffer{ d_Y, y_buf_offset, y_sz_total },
  5844. vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23},
  5845. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  5846. },
  5847. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  5848. if (x_non_contig) {
  5849. ctx->prealloc_x_need_sync = true;
  5850. }
  5851. if (y_non_contig || quantize_y) {
  5852. ctx->prealloc_y_need_sync = true;
  5853. }
  5854. }
  5855. 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, bool dryrun = false) {
  5856. ggml_tensor * dst = cgraph->nodes[node_idx];
  5857. const ggml_tensor * src0 = dst->src[0];
  5858. const ggml_tensor * src1 = dst->src[1];
  5859. 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];
  5860. 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];
  5861. 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];
  5862. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5863. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  5864. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  5865. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  5866. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5867. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5868. const uint64_t ne00 = src0->ne[0];
  5869. const uint64_t ne01 = src0->ne[1];
  5870. const uint64_t ne02 = src0->ne[2];
  5871. // const uint64_t ne03 = src0->ne[3];
  5872. const uint64_t ne10 = src1->ne[0];
  5873. const uint64_t ne11 = src1->ne[1];
  5874. const uint64_t ne12 = src1->ne[2];
  5875. // const uint64_t ne13 = src1->ne[3];
  5876. GGML_ASSERT(ne11 == 1);
  5877. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5878. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5879. vk_buffer d_Qy = nullptr;
  5880. size_t qy_buf_offset = 0;
  5881. bool src1_uma = false;
  5882. if (ctx->device->uma) {
  5883. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5884. src1_uma = d_Qy != nullptr;
  5885. }
  5886. const uint64_t x_ne = ne00 * ne01 * ne02;
  5887. const uint64_t y_ne = ne10 * ne11 * ne12;
  5888. const uint64_t d_ne = ne01 * ne11 * ne12;
  5889. 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);
  5890. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5891. const uint64_t d_sz = sizeof(float) * d_ne;
  5892. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  5893. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  5894. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  5895. gqa_ratio = 1;
  5896. }
  5897. if (dryrun) {
  5898. // Request descriptor sets
  5899. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  5900. return;
  5901. }
  5902. vk_buffer d_D;
  5903. uint64_t d_buf_offset = 0;
  5904. if (ctx->num_additional_fused_ops > 0) {
  5905. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5906. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  5907. d_D = dst_buf_ctx->dev_buffer;
  5908. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  5909. } else {
  5910. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5911. d_D = dst_buf_ctx->dev_buffer;
  5912. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5913. }
  5914. GGML_ASSERT(d_D != nullptr);
  5915. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5916. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5917. GGML_ASSERT(d_Qx != nullptr);
  5918. if (!src1_uma) {
  5919. d_Qy = src1_buf_ctx->dev_buffer;
  5920. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5921. GGML_ASSERT(d_Qx != nullptr);
  5922. }
  5923. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5924. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5925. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5926. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5927. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  5928. vk_buffer d_B = d_D;
  5929. size_t b_buf_offset = 0;
  5930. uint64_t b_sz = 0;
  5931. if (enable_bias) {
  5932. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5933. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5934. bool b_uma = false;
  5935. if (ctx->device->uma) {
  5936. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  5937. b_uma = d_B != nullptr;
  5938. }
  5939. if(!b_uma) {
  5940. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  5941. d_B = bias_buf_ctx->dev_buffer;
  5942. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  5943. GGML_ASSERT(d_B != nullptr);
  5944. b_sz = ggml_nbytes(bias);
  5945. }
  5946. }
  5947. // compute
  5948. const std::array<uint32_t, 7> pc = { (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)), enable_bias };
  5949. uint32_t workgroups_z = (uint32_t)ne12;
  5950. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  5951. if (gqa_ratio > 1) {
  5952. workgroups_z /= gqa_ratio;
  5953. }
  5954. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  5955. {
  5956. vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz },
  5957. vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset },
  5958. vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset },
  5959. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  5960. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  5961. }
  5962. 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, bool dryrun = false) {
  5963. ggml_tensor * dst = cgraph->nodes[node_idx];
  5964. const ggml_tensor * src0 = dst->src[0];
  5965. const ggml_tensor * src1 = dst->src[1];
  5966. 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];
  5967. 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];
  5968. 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];
  5969. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5970. GGML_ASSERT(!ggml_is_transposed(src0));
  5971. GGML_ASSERT(!ggml_is_transposed(src1));
  5972. GGML_ASSERT(!ggml_is_permuted(src0));
  5973. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5974. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5975. const uint64_t ne00 = src0->ne[0];
  5976. const uint64_t ne01 = src0->ne[1];
  5977. const uint64_t ne02 = src0->ne[2];
  5978. const uint64_t ne03 = src0->ne[3];
  5979. const uint64_t nb01 = src0->nb[1];
  5980. const uint64_t nb02 = src0->nb[2];
  5981. const uint64_t nb12 = src1->nb[2];
  5982. // const uint64_t ne10 = src1->ne[0];
  5983. const uint64_t ne11 = src1->ne[1];
  5984. const uint64_t ne12 = src1->ne[2];
  5985. // const uint64_t ne13 = src1->ne[3];
  5986. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  5987. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  5988. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  5989. GGML_ASSERT(ne11 == 1);
  5990. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  5991. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5992. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5993. vk_buffer d_Qy = nullptr;
  5994. size_t qy_buf_offset = 0;
  5995. bool src1_uma = false;
  5996. if (ctx->device->uma) {
  5997. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5998. src1_uma = d_Qy != nullptr;
  5999. }
  6000. const uint64_t d_ne = ne01 * ne11 * ne12 * ne03;
  6001. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6002. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6003. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6004. const uint64_t qx_sz = ggml_nbytes(src0);
  6005. const uint64_t qy_sz = ggml_nbytes(src1);
  6006. const uint64_t d_sz = sizeof(float) * d_ne;
  6007. if (dryrun) {
  6008. // Request descriptor sets
  6009. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6010. return;
  6011. }
  6012. vk_buffer d_D;
  6013. uint64_t d_buf_offset = 0;
  6014. if (ctx->num_additional_fused_ops > 0) {
  6015. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6016. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  6017. d_D = dst_buf_ctx->dev_buffer;
  6018. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  6019. } else {
  6020. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6021. d_D = dst_buf_ctx->dev_buffer;
  6022. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6023. }
  6024. GGML_ASSERT(d_D != nullptr);
  6025. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  6026. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6027. GGML_ASSERT(d_Qx != nullptr);
  6028. if (!src1_uma) {
  6029. d_Qy = src1_buf_ctx->dev_buffer;
  6030. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6031. GGML_ASSERT(d_Qx != nullptr);
  6032. }
  6033. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  6034. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  6035. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  6036. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  6037. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  6038. vk_buffer d_B = d_D;
  6039. size_t b_buf_offset = 0;
  6040. uint64_t b_sz = 0;
  6041. if (enable_bias) {
  6042. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6043. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6044. bool b_uma = false;
  6045. if (ctx->device->uma) {
  6046. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  6047. b_uma = d_B != nullptr;
  6048. }
  6049. if(!b_uma) {
  6050. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  6051. d_B = bias_buf_ctx->dev_buffer;
  6052. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  6053. GGML_ASSERT(d_B != nullptr);
  6054. b_sz = ggml_nbytes(bias);
  6055. }
  6056. }
  6057. // compute
  6058. const std::array<uint32_t, 13> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, channel_stride_y, (uint32_t)(ne12 / ne02), (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)), nb03, nb13, nb23, enable_bias };
  6059. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6060. {
  6061. vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz },
  6062. vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset },
  6063. vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset },
  6064. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  6065. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6066. }
  6067. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  6068. ggml_tensor * dst = cgraph->nodes[node_idx];
  6069. ggml_tensor * src0 = dst->src[0];
  6070. ggml_tensor * src1 = dst->src[1];
  6071. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6072. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6073. // where the M dimension is very large.
  6074. // Split_k doesn't work with M splitting.
  6075. const size_t nbytes = ggml_nbytes(src0);
  6076. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6077. if (needs_split) {
  6078. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6079. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6080. uint32_t m_offset = 0;
  6081. while (m_offset < dst->ne[0]) {
  6082. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6083. ggml_tensor dst2 = *dst;
  6084. ggml_tensor src02 = *src0;
  6085. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6086. src02.view_src = src0->view_src ? src0->view_src : src0;
  6087. dst2.view_offs += m_offset * dst->nb[0];
  6088. src02.view_offs += m_offset * src0->nb[1];
  6089. dst2.ne[0] = cur_M_size;
  6090. src02.ne[1] = cur_M_size;
  6091. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true, dryrun);
  6092. m_offset += cur_M_size;
  6093. }
  6094. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6095. // detect 0213 permutation, and batch size of 1
  6096. src0->nb[0] <= src0->nb[2] &&
  6097. src0->nb[2] <= src0->nb[1] &&
  6098. src0->nb[1] <= src0->nb[3] &&
  6099. src1->nb[0] <= src1->nb[2] &&
  6100. src1->nb[2] <= src1->nb[1] &&
  6101. src1->nb[1] <= src1->nb[3] &&
  6102. src0->ne[3] == 1 &&
  6103. src1->ne[3] == 1) {
  6104. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx, dryrun);
  6105. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6106. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6107. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx, dryrun);
  6108. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6109. // when ne12 and ne13 are one.
  6110. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6111. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6112. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx, dryrun);
  6113. } else {
  6114. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false, dryrun);
  6115. }
  6116. }
  6117. static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, bool dryrun = false) {
  6118. 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];
  6119. 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];
  6120. 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];
  6121. 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] << "),)");
  6122. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6123. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6124. const uint64_t ne00 = src0->ne[0];
  6125. const uint64_t ne01 = src0->ne[1];
  6126. const uint64_t ne02 = src0->ne[2];
  6127. const uint64_t ne03 = src0->ne[3];
  6128. const uint64_t ne10 = src1->ne[0];
  6129. const uint64_t ne11 = src1->ne[1];
  6130. const uint64_t ne12 = src1->ne[2];
  6131. const uint64_t ne13 = src1->ne[3];
  6132. const uint64_t nei0 = ids->ne[0];
  6133. const uint64_t nei1 = ids->ne[1];
  6134. const uint32_t nbi1 = ids->nb[1];
  6135. const uint32_t nbi2 = ids->nb[2];
  6136. const uint64_t ne20 = dst->ne[0];
  6137. const uint64_t ne21 = dst->ne[1];
  6138. const uint64_t ne22 = dst->ne[2];
  6139. const uint64_t ne23 = dst->ne[3];
  6140. const uint64_t n_as = ne02;
  6141. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6142. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6143. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6144. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6145. vk_buffer d_Qx = nullptr;
  6146. size_t qx_buf_offset = 0;
  6147. vk_buffer d_Qy = nullptr;
  6148. size_t qy_buf_offset = 0;
  6149. vk_buffer d_ids = nullptr;
  6150. size_t ids_buf_offset = 0;
  6151. bool src0_uma = false;
  6152. bool src1_uma = false;
  6153. bool ids_uma = false;
  6154. if (ctx->device->uma) {
  6155. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6156. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6157. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6158. src0_uma = d_Qx != nullptr;
  6159. src1_uma = d_Qy != nullptr;
  6160. ids_uma = d_ids != nullptr;
  6161. }
  6162. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6163. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6164. !ggml_vk_dim01_contiguous(src0);
  6165. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6166. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6167. !ggml_vk_dim01_contiguous(src1);
  6168. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6169. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6170. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6171. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  6172. // Check for mmq first
  6173. 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;
  6174. if (mmp == nullptr) {
  6175. // Fall back to f16 dequant mul mat
  6176. 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]);
  6177. quantize_y = false;
  6178. }
  6179. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6180. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6181. if (qx_needs_dequant) {
  6182. // Fall back to dequant + f16 mulmat
  6183. 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]);
  6184. }
  6185. // Not implemented
  6186. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6187. 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));
  6188. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6189. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6190. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6191. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6192. const uint64_t x_ne = ne01 * ne00;
  6193. const uint64_t y_ne = padded_n * ne10;
  6194. const uint64_t d_ne = ne21 * ne20;
  6195. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6196. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6197. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6198. const uint64_t y_sz = quantize_y ? (y_ne * 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);
  6199. const uint64_t ids_sz = nbi2;
  6200. const uint64_t d_sz = sizeof(float) * d_ne;
  6201. vk_pipeline to_fp16_vk_0 = nullptr;
  6202. vk_pipeline to_fp16_vk_1 = nullptr;
  6203. vk_pipeline to_q8_1 = nullptr;
  6204. if (x_non_contig) {
  6205. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6206. } else {
  6207. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6208. }
  6209. if (y_non_contig) {
  6210. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6211. } else {
  6212. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6213. }
  6214. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6215. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6216. if (quantize_y) {
  6217. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  6218. }
  6219. if (dryrun) {
  6220. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  6221. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  6222. if (quantize_y) {
  6223. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  6224. }
  6225. if (
  6226. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  6227. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  6228. GGML_ABORT("Requested preallocation size is too large");
  6229. }
  6230. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  6231. ctx->prealloc_size_x = x_sz_upd;
  6232. }
  6233. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  6234. ctx->prealloc_size_y = y_sz_upd;
  6235. }
  6236. // Request descriptor sets
  6237. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6238. if (qx_needs_dequant) {
  6239. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6240. }
  6241. if (qy_needs_dequant) {
  6242. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6243. }
  6244. if (quantize_y) {
  6245. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6246. }
  6247. return;
  6248. }
  6249. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6250. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6251. GGML_ASSERT(d_D != nullptr);
  6252. vk_buffer d_X;
  6253. uint64_t x_buf_offset = 0;
  6254. vk_buffer d_Y;
  6255. uint64_t y_buf_offset = 0;
  6256. if (!src0_uma) {
  6257. d_Qx = src0_buf_ctx->dev_buffer;
  6258. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6259. GGML_ASSERT(d_Qx != nullptr);
  6260. }
  6261. if (!src1_uma) {
  6262. d_Qy = src1_buf_ctx->dev_buffer;
  6263. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6264. GGML_ASSERT(d_Qy != nullptr);
  6265. }
  6266. if (!ids_uma) {
  6267. d_ids = ids_buf_ctx->dev_buffer;
  6268. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6269. GGML_ASSERT(d_ids != nullptr);
  6270. }
  6271. if (qx_needs_dequant) {
  6272. d_X = ctx->prealloc_x;
  6273. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  6274. } else {
  6275. d_X = d_Qx;
  6276. x_buf_offset = qx_buf_offset;
  6277. GGML_ASSERT(qx_sz == x_sz);
  6278. }
  6279. if (qy_needs_dequant) {
  6280. d_Y = ctx->prealloc_y;
  6281. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  6282. } else if (quantize_y) {
  6283. d_Y = ctx->prealloc_y;
  6284. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  6285. } else {
  6286. d_Y = d_Qy;
  6287. y_buf_offset = qy_buf_offset;
  6288. GGML_ASSERT(qy_sz == y_sz);
  6289. }
  6290. if (x_non_contig || qx_needs_dequant) {
  6291. if (ctx->prealloc_x_need_sync) {
  6292. ggml_vk_sync_buffers(ctx, subctx);
  6293. }
  6294. }
  6295. if (x_non_contig) {
  6296. 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));
  6297. } else if (qx_needs_dequant) {
  6298. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6299. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6300. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc, { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  6301. ggml_vk_sync_buffers(ctx, subctx);
  6302. }
  6303. if (y_non_contig) {
  6304. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6305. ctx->prealloc_y_last_tensor_used != src1) {
  6306. if (ctx->prealloc_y_need_sync) {
  6307. ggml_vk_sync_buffers(ctx, subctx);
  6308. }
  6309. 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));
  6310. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6311. ctx->prealloc_y_last_tensor_used = src1;
  6312. }
  6313. }
  6314. if (quantize_y) {
  6315. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6316. ctx->prealloc_y_last_tensor_used != src1) {
  6317. if (ctx->prealloc_y_need_sync) {
  6318. ggml_vk_sync_buffers(ctx, subctx);
  6319. }
  6320. 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 * ne12 * ne13, true);
  6321. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6322. ctx->prealloc_y_last_tensor_used = src1;
  6323. }
  6324. }
  6325. uint32_t stride_batch_x = ne00*ne01;
  6326. uint32_t stride_batch_y = ne10*ne11;
  6327. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6328. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6329. }
  6330. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6331. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6332. }
  6333. uint32_t y_sz_total = y_sz * ne12 * ne13;
  6334. if (quantize_y) {
  6335. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  6336. }
  6337. // compute
  6338. ggml_vk_matmul_id(
  6339. ctx, subctx, pipeline,
  6340. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz_total },
  6341. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  6342. ne01, ne21, ne10, ne10, ne10, ne01,
  6343. stride_batch_x, stride_batch_y, ne20*ne21,
  6344. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6345. ); // NOLINT
  6346. if (x_non_contig || qx_needs_dequant) {
  6347. ctx->prealloc_x_need_sync = true;
  6348. }
  6349. if (y_non_contig) {
  6350. ctx->prealloc_y_need_sync = true;
  6351. }
  6352. }
  6353. 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, bool dryrun = false) {
  6354. ggml_tensor * dst = cgraph->nodes[node_idx];
  6355. ggml_tensor * src0 = dst->src[0];
  6356. ggml_tensor * src1 = dst->src[1];
  6357. ggml_tensor * ids = dst->src[2];
  6358. 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];
  6359. 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];
  6360. 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];
  6361. 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];
  6362. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  6363. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6364. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6365. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6366. const uint64_t ne00 = src0->ne[0];
  6367. const uint64_t ne01 = src0->ne[1];
  6368. const uint64_t ne02 = src0->ne[2];
  6369. const uint64_t ne03 = src0->ne[3];
  6370. const uint64_t ne10 = src1->ne[0];
  6371. const uint64_t ne11 = src1->ne[1];
  6372. const uint64_t ne12 = src1->ne[2];
  6373. const uint64_t ne13 = src1->ne[3];
  6374. const uint64_t nei0 = ids->ne[0];
  6375. const uint64_t nei1 = ids->ne[1];
  6376. const uint64_t nbi2 = ids->nb[2];
  6377. GGML_ASSERT(nei1 == 1);
  6378. const uint64_t ne20 = dst->ne[0];
  6379. const uint64_t ne21 = dst->ne[1];
  6380. const uint64_t ne22 = dst->ne[2];
  6381. const uint64_t ne23 = dst->ne[3];
  6382. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6383. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6384. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6385. vk_buffer d_Qx = nullptr;
  6386. size_t qx_buf_offset = 0;
  6387. vk_buffer d_Qy = nullptr;
  6388. size_t qy_buf_offset = 0;
  6389. vk_buffer d_ids = nullptr;
  6390. size_t ids_buf_offset = 0;
  6391. bool src0_uma = false;
  6392. bool src1_uma = false;
  6393. bool ids_uma = false;
  6394. if (ctx->device->uma) {
  6395. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6396. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6397. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6398. src0_uma = d_Qx != nullptr;
  6399. src1_uma = d_Qy != nullptr;
  6400. ids_uma = d_ids != nullptr;
  6401. }
  6402. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6403. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6404. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6405. const bool qx_needs_dequant = x_non_contig;
  6406. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  6407. // Not implemented
  6408. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6409. const uint64_t x_ne = ne01 * ne00;
  6410. const uint64_t y_ne = ne11 * ne10;
  6411. const uint64_t d_ne = ne21 * ne20;
  6412. 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);
  6413. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6414. 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;
  6415. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  6416. const uint64_t ids_sz = nbi2;
  6417. const uint64_t d_sz = sizeof(float) * d_ne;
  6418. vk_pipeline to_fp16_vk_0 = nullptr;
  6419. vk_pipeline to_fp16_vk_1 = nullptr;
  6420. if (x_non_contig) {
  6421. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6422. }
  6423. if (y_non_contig) {
  6424. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6425. } else {
  6426. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6427. }
  6428. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  6429. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6430. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6431. GGML_ASSERT(dmmv != nullptr);
  6432. if (dryrun) {
  6433. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  6434. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  6435. if (
  6436. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  6437. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  6438. GGML_ABORT("Requested preallocation size is too large");
  6439. }
  6440. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  6441. ctx->prealloc_size_x = x_sz_upd;
  6442. }
  6443. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  6444. ctx->prealloc_size_y = y_sz_upd;
  6445. }
  6446. // Request descriptor sets
  6447. if (qx_needs_dequant) {
  6448. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6449. }
  6450. if (qy_needs_dequant) {
  6451. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6452. }
  6453. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6454. return;
  6455. }
  6456. vk_buffer d_D;
  6457. uint64_t d_buf_offset = 0;
  6458. if (ctx->num_additional_fused_ops > 0) {
  6459. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6460. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  6461. d_D = dst_buf_ctx->dev_buffer;
  6462. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  6463. } else {
  6464. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6465. d_D = dst_buf_ctx->dev_buffer;
  6466. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6467. }
  6468. GGML_ASSERT(d_D != nullptr);
  6469. vk_buffer d_X;
  6470. uint64_t x_buf_offset = 0;
  6471. vk_buffer d_Y;
  6472. uint64_t y_buf_offset = 0;
  6473. if(!src0_uma) {
  6474. d_Qx = src0_buf_ctx->dev_buffer;
  6475. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6476. GGML_ASSERT(d_Qx != nullptr);
  6477. }
  6478. if(!src1_uma) {
  6479. d_Qy = src1_buf_ctx->dev_buffer;
  6480. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6481. GGML_ASSERT(d_Qy != nullptr);
  6482. }
  6483. if(!ids_uma) {
  6484. d_ids = ids_buf_ctx->dev_buffer;
  6485. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6486. GGML_ASSERT(d_ids != nullptr);
  6487. }
  6488. if (qx_needs_dequant) {
  6489. d_X = ctx->prealloc_x;
  6490. } else {
  6491. d_X = d_Qx;
  6492. x_buf_offset = qx_buf_offset;
  6493. GGML_ASSERT(qx_sz == x_sz);
  6494. }
  6495. if (qy_needs_dequant) {
  6496. d_Y = ctx->prealloc_y;
  6497. } else {
  6498. d_Y = d_Qy;
  6499. y_buf_offset = qy_buf_offset;
  6500. GGML_ASSERT(qy_sz == y_sz);
  6501. }
  6502. if (x_non_contig) {
  6503. if (ctx->prealloc_x_need_sync) {
  6504. ggml_vk_sync_buffers(ctx, subctx);
  6505. }
  6506. }
  6507. if (x_non_contig) {
  6508. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6509. 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));
  6510. }
  6511. if (y_non_contig) {
  6512. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6513. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6514. ctx->prealloc_y_last_tensor_used != src1) {
  6515. if (ctx->prealloc_y_need_sync) {
  6516. ggml_vk_sync_buffers(ctx, subctx);
  6517. }
  6518. 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));
  6519. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6520. ctx->prealloc_y_last_tensor_used = src1;
  6521. }
  6522. }
  6523. uint32_t stride_batch_y = ne10*ne11;
  6524. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6525. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6526. }
  6527. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6528. uint32_t groups_x = ne01;
  6529. uint32_t groups_z = 1;
  6530. if (ne01 > max_groups_x) {
  6531. groups_z = 64;
  6532. groups_x = CEIL_DIV(groups_x, groups_z);
  6533. }
  6534. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  6535. vk_buffer d_B = d_D;
  6536. size_t b_buf_offset = 0;
  6537. uint64_t b_sz = 0;
  6538. if (enable_bias) {
  6539. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6540. bool b_uma = false;
  6541. if (ctx->device->uma) {
  6542. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  6543. b_uma = d_B != nullptr;
  6544. }
  6545. if(!b_uma) {
  6546. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  6547. d_B = bias_buf_ctx->dev_buffer;
  6548. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  6549. GGML_ASSERT(d_B != nullptr);
  6550. b_sz = ggml_nbytes(bias);
  6551. }
  6552. }
  6553. // compute
  6554. const vk_mat_vec_id_push_constants pc = {
  6555. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6556. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  6557. enable_bias,
  6558. (uint32_t)nei0, (uint32_t)ne11,
  6559. };
  6560. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6561. {
  6562. vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  6563. vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  6564. vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23},
  6565. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  6566. vk_subbuffer{ d_ids, ids_buf_offset, ids_sz },
  6567. },
  6568. pc, { groups_x, (uint32_t)nei0, groups_z });
  6569. if (x_non_contig) {
  6570. ctx->prealloc_x_need_sync = true;
  6571. }
  6572. if (y_non_contig) {
  6573. ctx->prealloc_y_need_sync = true;
  6574. }
  6575. }
  6576. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  6577. ggml_tensor * dst = cgraph->nodes[node_idx];
  6578. ggml_tensor * src0 = dst->src[0];
  6579. ggml_tensor * src2 = dst->src[2];
  6580. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  6581. }
  6582. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  6583. ggml_tensor * dst = cgraph->nodes[node_idx];
  6584. ggml_tensor * src0 = dst->src[0];
  6585. ggml_tensor * src1 = dst->src[1];
  6586. ggml_tensor * src2 = dst->src[2];
  6587. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6588. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  6589. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx, dryrun);
  6590. } else {
  6591. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  6592. }
  6593. }
  6594. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6595. // Needs to be kept up to date on shader changes
  6596. GGML_UNUSED(hsv);
  6597. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6598. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  6599. const uint32_t Bc = scalar_flash_attention_Bc;
  6600. const uint32_t tmpsh = wg_size * sizeof(float);
  6601. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6602. const uint32_t masksh = Bc * Br * sizeof(float);
  6603. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6604. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6605. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6606. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6607. return supported;
  6608. }
  6609. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6610. // Needs to be kept up to date on shader changes
  6611. GGML_UNUSED(hsv);
  6612. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6613. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6614. const uint32_t Bc = scalar_flash_attention_Bc;
  6615. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6616. const uint32_t acctype = f32acc ? 4 : 2;
  6617. const uint32_t f16vec4 = 8;
  6618. const uint32_t tmpsh = wg_size * sizeof(float);
  6619. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6620. const uint32_t qstride = hsk_pad / 4 + 2;
  6621. const uint32_t Qf = Br * qstride * f16vec4;
  6622. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6623. const uint32_t sfsh = Bc * sfshstride * acctype;
  6624. const uint32_t kshstride = hsk_pad / 4 + 2;
  6625. const uint32_t ksh = Bc * kshstride * f16vec4;
  6626. const uint32_t slope = Br * sizeof(float);
  6627. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6628. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6629. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6630. return supported;
  6631. }
  6632. 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, bool dryrun = false) {
  6633. 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];
  6634. 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];
  6635. 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];
  6636. 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];
  6637. if (sinks) {
  6638. 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];
  6639. }
  6640. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  6641. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6642. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6643. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6644. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6645. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6646. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6647. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6648. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6649. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6650. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6651. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6652. const uint32_t HSK = nek0;
  6653. const uint32_t HSV = nev0;
  6654. uint32_t N = neq1;
  6655. const uint32_t KV = nek1;
  6656. GGML_ASSERT(ne0 == HSV);
  6657. GGML_ASSERT(ne2 == N);
  6658. // input tensor rows must be contiguous
  6659. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6660. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6661. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6662. GGML_ASSERT(neq0 == HSK);
  6663. GGML_ASSERT(neq1 == N);
  6664. GGML_ASSERT(nev1 == nek1);
  6665. // dst cannot be transposed or permuted
  6666. GGML_ASSERT(nb0 == sizeof(float));
  6667. GGML_ASSERT(nb0 <= nb1);
  6668. GGML_ASSERT(nb1 <= nb2);
  6669. GGML_ASSERT(nb2 <= nb3);
  6670. assert(dst->type == GGML_TYPE_F32);
  6671. assert(q->type == GGML_TYPE_F32);
  6672. assert(k->type == v->type);
  6673. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6674. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6675. if (path == FA_COOPMAT1) {
  6676. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6677. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6678. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6679. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6680. path = FA_SCALAR;
  6681. }
  6682. }
  6683. uint32_t gqa_ratio = 1;
  6684. uint32_t qk_ratio = neq2 / nek2;
  6685. uint32_t workgroups_x = (uint32_t)neq1;
  6686. uint32_t workgroups_y = (uint32_t)neq2;
  6687. uint32_t workgroups_z = (uint32_t)neq3;
  6688. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6689. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6690. uint32_t max_gqa;
  6691. switch (path) {
  6692. case FA_SCALAR:
  6693. case FA_COOPMAT1:
  6694. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6695. max_gqa = get_fa_scalar_num_large_rows(HSV);
  6696. break;
  6697. case FA_COOPMAT2:
  6698. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6699. break;
  6700. default:
  6701. GGML_ASSERT(0);
  6702. }
  6703. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6704. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6705. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6706. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6707. // and change addressing calculations to index Q's dimension 2.
  6708. gqa_ratio = qk_ratio;
  6709. N = gqa_ratio;
  6710. workgroups_y /= N;
  6711. }
  6712. bool small_rows = N <= get_fa_num_small_rows(path);
  6713. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6714. // So use scalar instead.
  6715. if (small_rows && path == FA_COOPMAT1) {
  6716. path = FA_SCALAR;
  6717. }
  6718. // scalar is faster than coopmat2 when N==1
  6719. if (N == 1 && path == FA_COOPMAT2) {
  6720. path = FA_SCALAR;
  6721. }
  6722. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6723. if (path == FA_SCALAR &&
  6724. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6725. small_rows = true;
  6726. }
  6727. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6728. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6729. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6730. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  6731. if (k->type == GGML_TYPE_F32) {
  6732. k_stride /= 4;
  6733. }
  6734. if (v->type == GGML_TYPE_F32) {
  6735. v_stride /= 4;
  6736. }
  6737. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6738. bool aligned = (KV % alignment) == 0 &&
  6739. // the "aligned" shader variant will forcibly align strides, for performance
  6740. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6741. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6742. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6743. aligned = false;
  6744. }
  6745. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6746. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6747. vk_pipeline pipeline = nullptr;
  6748. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6749. auto it = pipelines.find(fa_pipeline_state);
  6750. if (it != pipelines.end()) {
  6751. pipeline = it->second;
  6752. } else {
  6753. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6754. }
  6755. assert(pipeline);
  6756. uint32_t split_kv = KV;
  6757. uint32_t split_k = 1;
  6758. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6759. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6760. // Try to use split_k when KV is large enough to be worth the overhead
  6761. if (workgroups_x == 1 && shader_core_count > 0) {
  6762. // Try to run two workgroups per SM.
  6763. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6764. if (split_k > 1) {
  6765. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6766. // of "align", so recompute split_k based on that.
  6767. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6768. split_k = CEIL_DIV(KV, split_kv);
  6769. workgroups_x = split_k;
  6770. }
  6771. }
  6772. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  6773. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  6774. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  6775. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  6776. GGML_ABORT("Requested preallocation size is too large");
  6777. }
  6778. if (ctx->prealloc_size_split_k < split_k_size) {
  6779. ctx->prealloc_size_split_k = split_k_size;
  6780. }
  6781. if (dryrun) {
  6782. // Request descriptor sets
  6783. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6784. if (split_k > 1) {
  6785. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  6786. }
  6787. return;
  6788. }
  6789. float scale = 1.0f;
  6790. float max_bias = 0.0f;
  6791. float logit_softcap = 0.0f;
  6792. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  6793. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  6794. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  6795. if (logit_softcap != 0) {
  6796. scale /= logit_softcap;
  6797. }
  6798. const uint32_t n_head_kv = neq2;
  6799. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  6800. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  6801. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  6802. vk_buffer d_Q = nullptr, d_K = nullptr, d_V = nullptr, d_D = nullptr, d_M = nullptr, d_S = nullptr;
  6803. size_t q_buf_offset = 0, k_buf_offset = 0, v_buf_offset = 0, d_buf_offset = 0, m_buf_offset = 0, s_buf_offset = 0;
  6804. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false, S_uma = false;
  6805. if (ctx->device->uma) {
  6806. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  6807. ggml_vk_host_get(ctx->device, k->data, d_K, k_buf_offset);
  6808. ggml_vk_host_get(ctx->device, v->data, d_V, v_buf_offset);
  6809. ggml_vk_host_get(ctx->device, dst->data, d_D, d_buf_offset);
  6810. Q_uma = d_Q != nullptr;
  6811. K_uma = d_K != nullptr;
  6812. V_uma = d_V != nullptr;
  6813. D_uma = d_D != nullptr;
  6814. if (mask) {
  6815. ggml_vk_host_get(ctx->device, mask->data, d_M, m_buf_offset);
  6816. M_uma = d_M != nullptr;
  6817. }
  6818. if (sinks) {
  6819. ggml_vk_host_get(ctx->device, sinks->data, d_S, s_buf_offset);
  6820. S_uma = d_S != nullptr;
  6821. }
  6822. }
  6823. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6824. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  6825. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  6826. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  6827. if (!Q_uma) {
  6828. d_Q = q_buf_ctx->dev_buffer;
  6829. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  6830. }
  6831. if (!K_uma) {
  6832. d_K = k_buf_ctx->dev_buffer;
  6833. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  6834. }
  6835. if (!V_uma) {
  6836. d_V = v_buf_ctx->dev_buffer;
  6837. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  6838. }
  6839. if (!D_uma) {
  6840. d_D = d_buf_ctx->dev_buffer;
  6841. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6842. }
  6843. if (!M_uma) {
  6844. d_M = d_Q;
  6845. m_buf_offset = q_buf_offset;
  6846. if (mask) {
  6847. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  6848. d_M = m_buf_ctx->dev_buffer;
  6849. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  6850. }
  6851. }
  6852. if (!S_uma) {
  6853. d_S = d_Q;
  6854. s_buf_offset = q_buf_offset;
  6855. if (sinks) {
  6856. ggml_backend_vk_buffer_context * s_buf_ctx = (ggml_backend_vk_buffer_context*)sinks->buffer->context;
  6857. d_S = s_buf_ctx->dev_buffer;
  6858. s_buf_offset = vk_tensor_offset(sinks) + sinks->view_offs;
  6859. }
  6860. }
  6861. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  6862. const vk_flash_attn_push_constants pc = { N, KV,
  6863. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  6864. (uint32_t)neq2, (uint32_t)neq3,
  6865. (uint32_t)nek2, (uint32_t)nek3,
  6866. (uint32_t)nev2, (uint32_t)nev3,
  6867. nem1, nem2, nem3,
  6868. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  6869. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  6870. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  6871. scale, max_bias, logit_softcap,
  6872. mask_n_head_log2, m0, m1,
  6873. gqa_ratio, split_kv, split_k };
  6874. if (split_k > 1) {
  6875. if (ctx->prealloc_split_k_need_sync) {
  6876. ggml_vk_sync_buffers(ctx, subctx);
  6877. }
  6878. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6879. {
  6880. ggml_vk_subbuffer(ctx, d_Q, q_buf_offset),
  6881. ggml_vk_subbuffer(ctx, d_K, k_buf_offset),
  6882. ggml_vk_subbuffer(ctx, d_V, v_buf_offset),
  6883. ggml_vk_subbuffer(ctx, d_M, m_buf_offset),
  6884. ggml_vk_subbuffer(ctx, d_S, s_buf_offset),
  6885. ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0),
  6886. },
  6887. // We only use split_k when group query attention is enabled, which means
  6888. // there's no more than one tile of rows (i.e. workgroups_x would have been
  6889. // one). We reuse workgroups_x to mean the number of splits, so we need to
  6890. // cancel out the divide by wg_denoms[0].
  6891. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  6892. ggml_vk_sync_buffers(ctx, subctx);
  6893. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  6894. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  6895. {
  6896. ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0),
  6897. ggml_vk_subbuffer(ctx, d_S, s_buf_offset),
  6898. ggml_vk_subbuffer(ctx, d_D, d_buf_offset),
  6899. },
  6900. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  6901. ctx->prealloc_split_k_need_sync = true;
  6902. } else {
  6903. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6904. {
  6905. ggml_vk_subbuffer(ctx, d_Q, q_buf_offset),
  6906. ggml_vk_subbuffer(ctx, d_K, k_buf_offset),
  6907. ggml_vk_subbuffer(ctx, d_V, v_buf_offset),
  6908. ggml_vk_subbuffer(ctx, d_M, m_buf_offset),
  6909. ggml_vk_subbuffer(ctx, d_S, s_buf_offset),
  6910. ggml_vk_subbuffer(ctx, d_D, d_buf_offset),
  6911. },
  6912. pc, { workgroups_x, workgroups_y, workgroups_z });
  6913. }
  6914. }
  6915. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  6916. const ggml_tensor *src0 = dst->src[0];
  6917. const ggml_tensor *src1 = dst->src[1];
  6918. // src0 - kernel: [KW, KH, Cin, Cout]
  6919. // src1 - input: [W, H, Cin, N]
  6920. // dst - result: [OW, OH, Cout, N]
  6921. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  6922. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6923. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  6924. };
  6925. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6926. int64_t W = src1->ne[0];
  6927. int64_t H = src1->ne[1];
  6928. int64_t KW = src0->ne[0];
  6929. int64_t KH = src0->ne[1];
  6930. int64_t Cout = src0->ne[3];
  6931. int64_t N = src1->ne[3];
  6932. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  6933. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  6934. int64_t NPQ = N * OW * OH;
  6935. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6936. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6937. return elements;
  6938. }
  6939. static std::array<uint32_t, 3> ggml_vk_get_conv_transpose_2d_elements(const ggml_tensor *dst) {
  6940. const ggml_tensor *src0 = dst->src[0];
  6941. const ggml_tensor *src1 = dst->src[1];
  6942. // src0 - kernel: [KW, KH, Cout, Cin]
  6943. // src1 - input: [W, H, Cin, N]
  6944. // dst - result: [OW, OH, Cout, N]
  6945. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6946. return (ins - 1) * s - 2 * p + (ks - 1) * d + 1;
  6947. };
  6948. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6949. int64_t W = src1->ne[0];
  6950. int64_t H = src1->ne[1];
  6951. int64_t KW = src0->ne[0];
  6952. int64_t KH = src0->ne[1];
  6953. int64_t Cout = src0->ne[2];
  6954. int64_t N = src1->ne[3];
  6955. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[0], 0, 1);
  6956. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], 0, 1);
  6957. int64_t NPQ = N * OW * OH;
  6958. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6959. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6960. return elements;
  6961. }
  6962. 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) {
  6963. switch (op) {
  6964. case GGML_OP_GET_ROWS:
  6965. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  6966. if (dst->type == GGML_TYPE_F16) {
  6967. return ctx->device->pipeline_get_rows[src0->type];
  6968. }
  6969. if (dst->type == GGML_TYPE_F32) {
  6970. return ctx->device->pipeline_get_rows_f32[src0->type];
  6971. }
  6972. return nullptr;
  6973. case GGML_OP_ACC:
  6974. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6975. return ctx->device->pipeline_acc_f32;
  6976. }
  6977. return nullptr;
  6978. case GGML_OP_ADD:
  6979. case GGML_OP_SUB:
  6980. case GGML_OP_MUL:
  6981. case GGML_OP_DIV:
  6982. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6983. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  6984. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  6985. return nullptr;
  6986. }
  6987. switch (op) {
  6988. case GGML_OP_ADD:
  6989. {
  6990. if (ctx->num_additional_fused_ops > 0) {
  6991. if (ctx->do_add_rms_partials) {
  6992. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  6993. } else {
  6994. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6995. }
  6996. }
  6997. if (ctx->do_add_rms_partials) {
  6998. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  6999. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7000. } else {
  7001. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  7002. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7003. }
  7004. }
  7005. case GGML_OP_SUB:
  7006. {
  7007. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  7008. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7009. }
  7010. case GGML_OP_MUL:
  7011. {
  7012. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  7013. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7014. }
  7015. case GGML_OP_DIV:
  7016. {
  7017. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  7018. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7019. }
  7020. default:
  7021. break;
  7022. }
  7023. return nullptr;
  7024. case GGML_OP_ADD_ID:
  7025. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7026. return ctx->device->pipeline_add_id_f32;
  7027. }
  7028. return nullptr;
  7029. case GGML_OP_CONCAT:
  7030. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7031. return ctx->device->pipeline_concat_f32;
  7032. }
  7033. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7034. return ctx->device->pipeline_concat_f16;
  7035. }
  7036. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7037. return ctx->device->pipeline_concat_i32;
  7038. }
  7039. return nullptr;
  7040. case GGML_OP_UPSCALE:
  7041. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7042. ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(dst, 0) & 0xFF);
  7043. switch (mode) {
  7044. case GGML_SCALE_MODE_NEAREST:
  7045. return ctx->device->pipeline_upscale_nearest_f32;
  7046. case GGML_SCALE_MODE_BILINEAR:
  7047. return ctx->device->pipeline_upscale_bilinear_f32;
  7048. default:
  7049. return nullptr;
  7050. }
  7051. }
  7052. return nullptr;
  7053. case GGML_OP_SCALE:
  7054. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7055. return ctx->device->pipeline_scale_f32;
  7056. }
  7057. return nullptr;
  7058. case GGML_OP_SQR:
  7059. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7060. return ctx->device->pipeline_sqr_f32;
  7061. }
  7062. return nullptr;
  7063. case GGML_OP_SQRT:
  7064. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7065. return ctx->device->pipeline_sqrt_f32;
  7066. }
  7067. return nullptr;
  7068. case GGML_OP_SIN:
  7069. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7070. return ctx->device->pipeline_sin_f32;
  7071. }
  7072. return nullptr;
  7073. case GGML_OP_COS:
  7074. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7075. return ctx->device->pipeline_cos_f32;
  7076. }
  7077. return nullptr;
  7078. case GGML_OP_CLAMP:
  7079. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7080. return ctx->device->pipeline_clamp_f32;
  7081. }
  7082. return nullptr;
  7083. case GGML_OP_PAD:
  7084. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7085. return ctx->device->pipeline_pad_f32;
  7086. }
  7087. return nullptr;
  7088. case GGML_OP_ROLL:
  7089. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7090. return ctx->device->pipeline_roll_f32;
  7091. }
  7092. return nullptr;
  7093. case GGML_OP_REPEAT:
  7094. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7095. return ctx->device->pipeline_repeat_f32;
  7096. }
  7097. return nullptr;
  7098. case GGML_OP_REPEAT_BACK:
  7099. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7100. return ctx->device->pipeline_repeat_back_f32;
  7101. }
  7102. return nullptr;
  7103. case GGML_OP_CPY:
  7104. case GGML_OP_CONT:
  7105. case GGML_OP_DUP:
  7106. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7107. case GGML_OP_SET_ROWS:
  7108. if (src1->type == GGML_TYPE_I64) {
  7109. return ctx->device->pipeline_set_rows_i64[dst->type];
  7110. } else {
  7111. return ctx->device->pipeline_set_rows_i32[dst->type];
  7112. }
  7113. case GGML_OP_SILU_BACK:
  7114. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7115. return ctx->device->pipeline_silu_back_f32;
  7116. }
  7117. return nullptr;
  7118. case GGML_OP_NORM:
  7119. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7120. return ctx->device->pipeline_norm_f32;
  7121. }
  7122. return nullptr;
  7123. case GGML_OP_GROUP_NORM:
  7124. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7125. return ctx->device->pipeline_group_norm_f32;
  7126. }
  7127. return nullptr;
  7128. case GGML_OP_RMS_NORM:
  7129. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7130. if (ctx->do_add_rms_partials) {
  7131. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7132. } else {
  7133. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7134. }
  7135. }
  7136. return nullptr;
  7137. case GGML_OP_RMS_NORM_BACK:
  7138. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7139. return ctx->device->pipeline_rms_norm_back_f32;
  7140. }
  7141. return nullptr;
  7142. case GGML_OP_L2_NORM:
  7143. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7144. return ctx->device->pipeline_l2_norm_f32;
  7145. }
  7146. return nullptr;
  7147. case GGML_OP_UNARY:
  7148. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7149. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7150. (src0->type != dst->type)) {
  7151. return nullptr;
  7152. }
  7153. switch (ggml_get_unary_op(dst)) {
  7154. case GGML_UNARY_OP_EXP:
  7155. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7156. case GGML_UNARY_OP_SILU:
  7157. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7158. case GGML_UNARY_OP_GELU:
  7159. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7160. case GGML_UNARY_OP_GELU_ERF:
  7161. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7162. case GGML_UNARY_OP_GELU_QUICK:
  7163. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7164. case GGML_UNARY_OP_RELU:
  7165. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7166. case GGML_UNARY_OP_TANH:
  7167. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7168. case GGML_UNARY_OP_SIGMOID:
  7169. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7170. case GGML_UNARY_OP_HARDSIGMOID:
  7171. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7172. case GGML_UNARY_OP_HARDSWISH:
  7173. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7174. default:
  7175. break;
  7176. }
  7177. return nullptr;
  7178. case GGML_OP_GLU:
  7179. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7180. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7181. (src0->type != dst->type)) {
  7182. return nullptr;
  7183. }
  7184. switch (ggml_get_glu_op(dst)) {
  7185. case GGML_GLU_OP_GEGLU:
  7186. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7187. case GGML_GLU_OP_REGLU:
  7188. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7189. case GGML_GLU_OP_SWIGLU:
  7190. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7191. case GGML_GLU_OP_SWIGLU_OAI:
  7192. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7193. case GGML_GLU_OP_GEGLU_ERF:
  7194. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7195. case GGML_GLU_OP_GEGLU_QUICK:
  7196. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7197. default:
  7198. break;
  7199. }
  7200. return nullptr;
  7201. case GGML_OP_DIAG_MASK_INF:
  7202. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7203. return ctx->device->pipeline_diag_mask_inf_f32;
  7204. }
  7205. return nullptr;
  7206. case GGML_OP_SOFT_MAX:
  7207. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7208. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7209. if (ctx->num_additional_fused_ops) {
  7210. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7211. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7212. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7213. return ctx->device->pipeline_topk_moe[idx][mode];
  7214. }
  7215. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7216. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7217. }
  7218. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7219. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7220. }
  7221. return nullptr;
  7222. case GGML_OP_SOFT_MAX_BACK:
  7223. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7224. return ctx->device->pipeline_soft_max_back_f32;
  7225. }
  7226. return nullptr;
  7227. case GGML_OP_ROPE:
  7228. case GGML_OP_ROPE_BACK:
  7229. {
  7230. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7231. const int mode = ((const int32_t *) rope->op_params)[2];
  7232. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7233. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7234. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7235. if (is_neox) {
  7236. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7237. return ctx->device->pipeline_rope_neox_f32;
  7238. }
  7239. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7240. return ctx->device->pipeline_rope_neox_f32_f16;
  7241. }
  7242. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7243. return ctx->device->pipeline_rope_neox_f16;
  7244. }
  7245. } else if (is_mrope && !is_vision) {
  7246. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7247. return ctx->device->pipeline_rope_multi_f32;
  7248. }
  7249. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7250. return ctx->device->pipeline_rope_multi_f16;
  7251. }
  7252. } else if (is_vision) {
  7253. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7254. return ctx->device->pipeline_rope_vision_f32;
  7255. }
  7256. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7257. return ctx->device->pipeline_rope_vision_f16;
  7258. }
  7259. } else {
  7260. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7261. return ctx->device->pipeline_rope_norm_f32;
  7262. }
  7263. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7264. return ctx->device->pipeline_rope_norm_f32_f16;
  7265. }
  7266. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7267. return ctx->device->pipeline_rope_norm_f16;
  7268. }
  7269. }
  7270. return nullptr;
  7271. }
  7272. case GGML_OP_ARGSORT:
  7273. if (ctx->num_additional_fused_ops) {
  7274. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7275. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7276. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7277. return ctx->device->pipeline_topk_moe[idx][mode];
  7278. }
  7279. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7280. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7281. return ctx->device->pipeline_argsort_f32[idx];
  7282. }
  7283. return nullptr;
  7284. case GGML_OP_SUM:
  7285. case GGML_OP_SUM_ROWS:
  7286. case GGML_OP_MEAN:
  7287. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7288. return ctx->device->pipeline_sum_rows_f32;
  7289. }
  7290. return nullptr;
  7291. case GGML_OP_ARGMAX:
  7292. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7293. return ctx->device->pipeline_argmax_f32;
  7294. }
  7295. return nullptr;
  7296. case GGML_OP_COUNT_EQUAL:
  7297. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7298. return ctx->device->pipeline_count_equal_i32;
  7299. }
  7300. return nullptr;
  7301. case GGML_OP_IM2COL:
  7302. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7303. return ctx->device->pipeline_im2col_f32;
  7304. }
  7305. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7306. return ctx->device->pipeline_im2col_f32_f16;
  7307. }
  7308. return nullptr;
  7309. case GGML_OP_IM2COL_3D:
  7310. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7311. return ctx->device->pipeline_im2col_3d_f32;
  7312. }
  7313. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7314. return ctx->device->pipeline_im2col_3d_f32_f16;
  7315. }
  7316. return nullptr;
  7317. case GGML_OP_TIMESTEP_EMBEDDING:
  7318. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7319. return ctx->device->pipeline_timestep_embedding_f32;
  7320. }
  7321. return nullptr;
  7322. case GGML_OP_CONV_TRANSPOSE_1D:
  7323. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7324. return ctx->device->pipeline_conv_transpose_1d_f32;
  7325. }
  7326. return nullptr;
  7327. case GGML_OP_POOL_2D:
  7328. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7329. return ctx->device->pipeline_pool2d_f32;
  7330. }
  7331. return nullptr;
  7332. case GGML_OP_RWKV_WKV6:
  7333. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7334. return ctx->device->pipeline_rwkv_wkv6_f32;
  7335. }
  7336. return nullptr;
  7337. case GGML_OP_RWKV_WKV7:
  7338. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7339. return ctx->device->pipeline_rwkv_wkv7_f32;
  7340. }
  7341. return nullptr;
  7342. case GGML_OP_SSM_SCAN:
  7343. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7344. const uint32_t d_state = src0->ne[0];
  7345. if (d_state == 128) {
  7346. return ctx->device->pipeline_ssm_scan_f32_d128;
  7347. } else if (d_state == 256) {
  7348. return ctx->device->pipeline_ssm_scan_f32_d256;
  7349. }
  7350. }
  7351. return nullptr;
  7352. case GGML_OP_SSM_CONV:
  7353. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7354. return ctx->device->pipeline_ssm_conv_f32;
  7355. }
  7356. return nullptr;
  7357. case GGML_OP_OPT_STEP_ADAMW:
  7358. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7359. return ctx->device->pipeline_opt_step_adamw_f32;
  7360. }
  7361. return nullptr;
  7362. case GGML_OP_OPT_STEP_SGD:
  7363. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7364. return ctx->device->pipeline_opt_step_sgd_f32;
  7365. }
  7366. return nullptr;
  7367. case GGML_OP_LEAKY_RELU:
  7368. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7369. return ctx->device->pipeline_leaky_relu_f32;
  7370. }
  7371. return nullptr;
  7372. case GGML_OP_CONV_2D:
  7373. case GGML_OP_CONV_TRANSPOSE_2D:
  7374. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  7375. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  7376. std::array<uint32_t, 3> elements;
  7377. if (op == GGML_OP_CONV_2D) elements = ggml_vk_get_conv_elements(dst);
  7378. else if (op == GGML_OP_CONV_TRANSPOSE_2D) elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7379. vk_conv_shapes shape;
  7380. uint32_t tiles[CONV_SHAPE_COUNT];
  7381. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  7382. tiles[i] = CEIL_DIV(elements[0], ctx->device->pipeline_conv2d_f32[i]->wg_denoms[0]) * CEIL_DIV(elements[1], ctx->device->pipeline_conv2d_f32[i]->wg_denoms[1]);
  7383. }
  7384. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7385. // so small convolutions will still choose a smaller tile.
  7386. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7387. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  7388. shape = CONV_SHAPE_128x128;
  7389. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  7390. shape = CONV_SHAPE_32x256;
  7391. } else {
  7392. shape = CONV_SHAPE_64x32;
  7393. }
  7394. if (op == GGML_OP_CONV_2D) {
  7395. if (src0->type == GGML_TYPE_F32) {
  7396. return ctx->device->pipeline_conv2d_f32[shape];
  7397. } else if (src0->type == GGML_TYPE_F16) {
  7398. return ctx->device->pipeline_conv2d_f16_f32[shape];
  7399. }
  7400. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7401. if (src0->type == GGML_TYPE_F32) {
  7402. return ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7403. } else if (src0->type == GGML_TYPE_F16) {
  7404. return ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7405. }
  7406. }
  7407. }
  7408. return nullptr;
  7409. case GGML_OP_CONV_2D_DW:
  7410. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7411. if (ggml_is_contiguous(src1)) {
  7412. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7413. } else if (ggml_is_contiguous_channels(src1)) {
  7414. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7415. }
  7416. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7417. if (ggml_is_contiguous(src1)) {
  7418. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7419. } else if (ggml_is_contiguous_channels(src1)) {
  7420. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7421. }
  7422. }
  7423. return nullptr;
  7424. default:
  7425. return nullptr;
  7426. }
  7427. GGML_UNUSED(src2);
  7428. }
  7429. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  7430. switch (op) {
  7431. case GGML_OP_CPY:
  7432. case GGML_OP_GET_ROWS:
  7433. case GGML_OP_ADD:
  7434. case GGML_OP_SUB:
  7435. case GGML_OP_MUL:
  7436. case GGML_OP_DIV:
  7437. case GGML_OP_ADD_ID:
  7438. case GGML_OP_CONCAT:
  7439. case GGML_OP_UPSCALE:
  7440. case GGML_OP_SQR:
  7441. case GGML_OP_SQRT:
  7442. case GGML_OP_SIN:
  7443. case GGML_OP_COS:
  7444. case GGML_OP_CLAMP:
  7445. case GGML_OP_PAD:
  7446. case GGML_OP_REPEAT:
  7447. case GGML_OP_REPEAT_BACK:
  7448. case GGML_OP_ROPE:
  7449. case GGML_OP_RMS_NORM:
  7450. case GGML_OP_CONV_2D_DW:
  7451. case GGML_OP_IM2COL:
  7452. case GGML_OP_IM2COL_3D:
  7453. case GGML_OP_SET_ROWS:
  7454. case GGML_OP_SUM:
  7455. case GGML_OP_SUM_ROWS:
  7456. case GGML_OP_MEAN:
  7457. return true;
  7458. default:
  7459. return false;
  7460. }
  7461. }
  7462. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  7463. {
  7464. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  7465. }
  7466. 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) {
  7467. GGML_UNUSED(p);
  7468. GGML_UNUSED(src0);
  7469. GGML_UNUSED(src1);
  7470. GGML_UNUSED(src2);
  7471. GGML_UNUSED(src3);
  7472. GGML_UNUSED(dst);
  7473. static_assert(!std::is_const<T>::value, "unexpected type");
  7474. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  7475. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  7476. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  7477. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  7478. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  7479. }
  7480. 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) {
  7481. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7482. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7483. p.misalign_offsets = (a_offset << 16) | d_offset;
  7484. GGML_UNUSED(src1);
  7485. GGML_UNUSED(src2);
  7486. GGML_UNUSED(src3);
  7487. }
  7488. 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) {
  7489. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7490. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7491. p.misalign_offsets = (a_offset << 16) | d_offset;
  7492. GGML_UNUSED(src1);
  7493. GGML_UNUSED(src2);
  7494. GGML_UNUSED(src3);
  7495. }
  7496. 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) {
  7497. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7498. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7499. p.misalign_offsets = (a_offset << 16) | d_offset;
  7500. GGML_UNUSED(src1);
  7501. GGML_UNUSED(src2);
  7502. GGML_UNUSED(src3);
  7503. }
  7504. 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) {
  7505. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7506. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7507. p.misalign_offsets = (a_offset << 16) | d_offset;
  7508. GGML_UNUSED(src0);
  7509. GGML_UNUSED(src2);
  7510. GGML_UNUSED(src3);
  7511. }
  7512. 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) {
  7513. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7514. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7515. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7516. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7517. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7518. GGML_UNUSED(src2);
  7519. GGML_UNUSED(src3);
  7520. }
  7521. 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) {
  7522. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7523. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7524. p.a_offset = a_offset;
  7525. p.d_offset = d_offset;
  7526. GGML_UNUSED(src1);
  7527. GGML_UNUSED(src2);
  7528. GGML_UNUSED(src3);
  7529. }
  7530. template<typename PC>
  7531. 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, bool dryrun = false) {
  7532. 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];
  7533. if (src1 != nullptr) {
  7534. 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];
  7535. }
  7536. if (src2 != nullptr) {
  7537. 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];
  7538. }
  7539. if (src3 != nullptr) {
  7540. 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];
  7541. }
  7542. 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];
  7543. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  7544. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7545. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  7546. GGML_ASSERT(dst->buffer != nullptr);
  7547. const uint64_t ne00 = src0->ne[0];
  7548. const uint64_t ne01 = src0->ne[1];
  7549. const uint64_t ne02 = src0->ne[2];
  7550. const uint64_t ne03 = src0->ne[3];
  7551. const uint64_t ne0 = ne00 * ne01;
  7552. const bool use_src1 = src1 != nullptr;
  7553. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7554. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7555. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7556. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7557. const uint64_t ne1 = ne10 * ne11;
  7558. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  7559. const bool use_src2 = src2 != nullptr;
  7560. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  7561. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  7562. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  7563. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  7564. const uint64_t ne2 = ne20 * ne21;
  7565. const bool use_src3 = src3 != nullptr;
  7566. const uint64_t ne30 = use_src3 ? src3->ne[0] : 0;
  7567. const uint64_t ne31 = use_src3 ? src3->ne[1] : 0;
  7568. const uint64_t ne32 = use_src3 ? src3->ne[2] : 0;
  7569. const uint64_t ne33 = use_src3 ? src3->ne[3] : 0;
  7570. const uint64_t ne3 = ne30 * ne31;
  7571. const uint64_t ned0 = dst->ne[0];
  7572. const uint64_t ned1 = dst->ne[1];
  7573. const uint64_t ned2 = dst->ne[2];
  7574. const uint64_t ned3 = dst->ne[3];
  7575. const uint64_t ned = ned0 * ned1;
  7576. init_pushconst_fastdiv(pc);
  7577. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7578. if (pipeline == nullptr) {
  7579. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7580. if (src1 != nullptr) {
  7581. std::cerr << " and " << ggml_type_name(src1->type);
  7582. }
  7583. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7584. GGML_ABORT("fatal error");
  7585. }
  7586. if (dryrun) {
  7587. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7588. return;
  7589. }
  7590. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  7591. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  7592. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  7593. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  7594. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  7595. ggml_backend_vk_buffer_context * src3_buf_ctx = use_src3 ? (ggml_backend_vk_buffer_context *)src3->buffer->context : nullptr;
  7596. vk_buffer d_X = nullptr;
  7597. size_t x_buf_offset = 0;
  7598. vk_buffer d_Y = nullptr;
  7599. size_t y_buf_offset = 0;
  7600. vk_buffer d_Z = nullptr;
  7601. size_t z_buf_offset = 0;
  7602. vk_buffer d_W = nullptr;
  7603. size_t w_buf_offset = 0;
  7604. bool src0_uma = false;
  7605. bool src1_uma = false;
  7606. bool src2_uma = false;
  7607. bool src3_uma = false;
  7608. if (ctx->device->uma) {
  7609. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  7610. src0_uma = d_X != nullptr;
  7611. if (use_src1) {
  7612. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  7613. src1_uma = d_Y != nullptr;
  7614. }
  7615. if (use_src2) {
  7616. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  7617. src2_uma = d_Z != nullptr;
  7618. }
  7619. if (use_src3) {
  7620. ggml_vk_host_get(ctx->device, src3->data, d_W, w_buf_offset);
  7621. src3_uma = d_W != nullptr;
  7622. }
  7623. }
  7624. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  7625. GGML_ASSERT(d_D != nullptr);
  7626. uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  7627. if(!src0_uma) {
  7628. d_X = src0_buf_ctx->dev_buffer;
  7629. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  7630. GGML_ASSERT(d_X != nullptr);
  7631. }
  7632. if (use_src1 && !src1_uma) {
  7633. d_Y = src1_buf_ctx->dev_buffer;
  7634. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  7635. GGML_ASSERT(d_Y != nullptr);
  7636. }
  7637. if (use_src2 && !src2_uma) {
  7638. d_Z = src2_buf_ctx->dev_buffer;
  7639. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  7640. GGML_ASSERT(d_Z != nullptr);
  7641. }
  7642. if (use_src3 && !src3_uma) {
  7643. d_W = src3_buf_ctx->dev_buffer;
  7644. w_buf_offset = vk_tensor_offset(src3) + src3->view_offs;
  7645. GGML_ASSERT(d_W != nullptr);
  7646. }
  7647. // Compute misalignment offset for descriptors and store it in in push constants, then align the descriptor offsets.
  7648. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7649. x_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7650. y_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7651. z_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7652. w_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7653. d_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7654. std::array<uint32_t, 3> elements;
  7655. // Single call if dimension 2 is contiguous
  7656. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  7657. switch (op) {
  7658. case GGML_OP_NORM:
  7659. case GGML_OP_RMS_NORM_BACK:
  7660. case GGML_OP_L2_NORM:
  7661. case GGML_OP_SOFT_MAX:
  7662. case GGML_OP_SOFT_MAX_BACK:
  7663. case GGML_OP_SUM_ROWS:
  7664. case GGML_OP_MEAN:
  7665. case GGML_OP_ARGMAX:
  7666. {
  7667. const uint32_t nr = ggml_nrows(src0);
  7668. if (nr > 262144) {
  7669. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7670. } else if (nr > 512) {
  7671. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7672. } else {
  7673. elements = { nr, 1, 1 };
  7674. }
  7675. } break;
  7676. case GGML_OP_RMS_NORM:
  7677. if (ctx->do_add_rms_partials) {
  7678. // Run one element per thread, 128 threads per workgroup
  7679. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7680. } else {
  7681. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7682. }
  7683. break;
  7684. case GGML_OP_SUM:
  7685. // We use GGML_OP_SUM_ROWS with 1 row.
  7686. elements = { 1, 1, 1 };
  7687. break;
  7688. case GGML_OP_GROUP_NORM:
  7689. {
  7690. const uint32_t num_groups = dst->op_params[0];
  7691. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7692. } break;
  7693. case GGML_OP_DIAG_MASK_INF:
  7694. case GGML_OP_ROPE:
  7695. case GGML_OP_ROPE_BACK:
  7696. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7697. break;
  7698. case GGML_OP_GET_ROWS:
  7699. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7700. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7701. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7702. break;
  7703. case GGML_OP_ARGSORT:
  7704. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  7705. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7706. break;
  7707. case GGML_OP_IM2COL:
  7708. {
  7709. const bool is_2D = dst->op_params[6] == 1;
  7710. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7711. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7712. const uint32_t KW = src0->ne[0];
  7713. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7714. const uint32_t OW = dst->ne[1];
  7715. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7716. elements = { OW * KW * KH, OH, batch * IC };
  7717. } break;
  7718. case GGML_OP_IM2COL_3D:
  7719. {
  7720. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7721. const uint32_t N = ne13 / IC;
  7722. const uint32_t KD = ne02;
  7723. const uint32_t KH = ne01;
  7724. const uint32_t KW = ne00;
  7725. const uint32_t OD = ned3 / N;
  7726. const uint32_t OH = ned2;
  7727. const uint32_t OW = ned1;
  7728. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7729. const uint32_t N_OD_OH = N*OD*OH;
  7730. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7731. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7732. } break;
  7733. case GGML_OP_TIMESTEP_EMBEDDING:
  7734. {
  7735. const uint32_t dim = dst->op_params[0];
  7736. uint32_t half_ceil = (dim + 1) / 2;
  7737. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7738. } break;
  7739. case GGML_OP_CONV_TRANSPOSE_1D:
  7740. {
  7741. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7742. } break;
  7743. case GGML_OP_POOL_2D:
  7744. {
  7745. const uint32_t N = dst->ne[3];
  7746. const uint32_t OC = dst->ne[2];
  7747. const uint32_t OH = dst->ne[1];
  7748. const uint32_t OW = dst->ne[0];
  7749. elements = { N * OC * OH * OW, 1, 1};
  7750. } break;
  7751. case GGML_OP_CONV_2D:
  7752. {
  7753. elements = ggml_vk_get_conv_elements(dst);
  7754. } break;
  7755. case GGML_OP_CONV_TRANSPOSE_2D:
  7756. {
  7757. elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7758. } break;
  7759. case GGML_OP_ADD:
  7760. case GGML_OP_SUB:
  7761. case GGML_OP_DIV:
  7762. case GGML_OP_MUL:
  7763. case GGML_OP_SCALE:
  7764. case GGML_OP_SQR:
  7765. case GGML_OP_SQRT:
  7766. case GGML_OP_SIN:
  7767. case GGML_OP_COS:
  7768. case GGML_OP_CLAMP:
  7769. case GGML_OP_PAD:
  7770. case GGML_OP_ROLL:
  7771. case GGML_OP_REPEAT:
  7772. case GGML_OP_REPEAT_BACK:
  7773. case GGML_OP_CPY:
  7774. case GGML_OP_CONCAT:
  7775. case GGML_OP_UPSCALE:
  7776. case GGML_OP_UNARY:
  7777. case GGML_OP_GLU:
  7778. case GGML_OP_CONV_2D_DW:
  7779. {
  7780. uint32_t ne = ggml_nelements(dst);
  7781. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7782. // Convert from number of logical elements to 2- or 4-byte units.
  7783. ne /= ggml_blck_size(src0->type);
  7784. if ((ggml_type_size(src0->type) % 4) == 0) {
  7785. ne *= ggml_type_size(src0->type) / 4;
  7786. } else {
  7787. ne *= ggml_type_size(src0->type) / 2;
  7788. }
  7789. }
  7790. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7791. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7792. // So divide by block size here before splitting into 512x512 groups.
  7793. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7794. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7795. }
  7796. if (ne > 262144) {
  7797. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7798. } else if (ne > 512) {
  7799. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7800. } else {
  7801. elements = { ne, 1, 1 };
  7802. }
  7803. } break;
  7804. case GGML_OP_ADD_ID:
  7805. {
  7806. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7807. } break;
  7808. case GGML_OP_SET_ROWS:
  7809. {
  7810. uint32_t ne = ggml_nelements(src0);
  7811. if (ggml_is_quantized(dst->type)) {
  7812. // quants run 32 threads each doing QUANT_K elements
  7813. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7814. } else {
  7815. // scalar types do one element per thread, running 512 threads
  7816. ne = CEIL_DIV(ne, 512);
  7817. }
  7818. if (ne > 262144) {
  7819. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7820. } else if (ne > 512) {
  7821. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7822. } else {
  7823. elements = { ne, 1, 1 };
  7824. }
  7825. }
  7826. break;
  7827. case GGML_OP_SSM_CONV:
  7828. {
  7829. const uint32_t nr = src0->ne[1];
  7830. const uint32_t n_t = dst->ne[1];
  7831. const uint32_t n_s = dst->ne[2];
  7832. elements = { nr, n_t, n_s };
  7833. }
  7834. break;
  7835. default:
  7836. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7837. break;
  7838. }
  7839. uint64_t x_sz, y_sz, z_sz, w_sz, d_sz;
  7840. if (op_supports_incontiguous) {
  7841. x_sz = ggml_nbytes(src0) + get_misalign_bytes(ctx, src0);
  7842. y_sz = use_src1 ? ggml_nbytes(src1) + get_misalign_bytes(ctx, src1) : 0;
  7843. z_sz = use_src2 ? ggml_nbytes(src2) + get_misalign_bytes(ctx, src2) : 0;
  7844. w_sz = use_src3 ? ggml_nbytes(src3) + get_misalign_bytes(ctx, src3) : 0;
  7845. d_sz = ggml_nbytes(dst) + get_misalign_bytes(ctx, dst);
  7846. if (x_buf_offset + x_sz >= d_X->size) {
  7847. x_sz = ggml_vk_get_max_buffer_range(ctx, d_X, x_buf_offset);
  7848. }
  7849. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  7850. y_sz = ggml_vk_get_max_buffer_range(ctx, d_Y, y_buf_offset);
  7851. }
  7852. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  7853. z_sz = ggml_vk_get_max_buffer_range(ctx, d_Z, z_buf_offset);
  7854. }
  7855. if (use_src3 && w_buf_offset + w_sz >= d_W->size) {
  7856. w_sz = ggml_vk_get_max_buffer_range(ctx, d_W, w_buf_offset);
  7857. }
  7858. if (d_buf_offset + d_sz >= d_D->size) {
  7859. d_sz = ggml_vk_get_max_buffer_range(ctx, d_D, d_buf_offset);
  7860. }
  7861. } else {
  7862. x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0 * ne02 * ne03;
  7863. y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 * ne12 * ne13 : 0;
  7864. z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 * ne22 * ne23 : 0;
  7865. w_sz = use_src3 ? ggml_type_size(src3->type) * ne3 * ne32 * ne33 : 0;
  7866. d_sz = ggml_type_size(dst->type) * ned * ned2 * ned3;
  7867. }
  7868. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7869. vk_buffer d_A = ctx->do_add_rms_partials ? ctx->prealloc_add_rms_partials : d_X;
  7870. size_t a_buf_offset = ctx->do_add_rms_partials ? ctx->prealloc_size_add_rms_partials_offset : 0;
  7871. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7872. { vk_subbuffer{ d_X, x_buf_offset, x_sz },
  7873. vk_subbuffer{ d_Y, y_buf_offset, y_sz },
  7874. vk_subbuffer{ d_D, d_buf_offset, d_sz },
  7875. ggml_vk_subbuffer(ctx, d_A, a_buf_offset),
  7876. }, pc, elements);
  7877. } else if (op == GGML_OP_GLU) {
  7878. // Empty src1 is possible in glu, but the shader needs a buffer
  7879. vk_subbuffer subbuf_y;
  7880. if (use_src1) {
  7881. subbuf_y = { d_Y, y_buf_offset, y_sz };
  7882. } else {
  7883. subbuf_y = { d_X, 0, x_sz };
  7884. }
  7885. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7886. } else if (op == GGML_OP_SOFT_MAX) {
  7887. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7888. vk_subbuffer subbuf_y;
  7889. if (use_src1) {
  7890. subbuf_y = { d_Y, y_buf_offset, y_sz };
  7891. } else {
  7892. subbuf_y = { d_X, 0, x_sz };
  7893. }
  7894. vk_subbuffer subbuf_z;
  7895. if (use_src2) {
  7896. subbuf_z = { d_Z, z_buf_offset, z_sz };
  7897. } else {
  7898. subbuf_z = { d_X, 0, x_sz };
  7899. }
  7900. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, subbuf_z, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7901. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7902. // Empty src2 is possible in rope, but the shader needs a buffer
  7903. vk_subbuffer subbuf_z, subbuf_w;
  7904. if (use_src2) {
  7905. subbuf_z = { d_Z, z_buf_offset, z_sz };
  7906. } else {
  7907. subbuf_z = { d_X, 0, x_sz };
  7908. }
  7909. if (use_src3) {
  7910. subbuf_w = { d_W, w_buf_offset, w_sz };
  7911. } else {
  7912. subbuf_w = { d_X, 0, x_sz };
  7913. }
  7914. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, subbuf_z, vk_subbuffer{ d_D, d_buf_offset, d_sz }, subbuf_w }, pc, elements);
  7915. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7916. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7917. // buffer device address path doesn't use dst buffer
  7918. d_sz = 1;
  7919. }
  7920. // im2col uses only src1 and dst buffers
  7921. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7922. } else if (op == GGML_OP_COUNT_EQUAL) {
  7923. // count_equal assumes that destination buffer is initialized with zeroes
  7924. ggml_vk_buffer_memset_async(subctx, d_D, d_buf_offset, 0, d_sz);
  7925. ggml_vk_sync_buffers(ctx, subctx);
  7926. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7927. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7928. // OPT_STEP_SGD works on src0, it does not need dst
  7929. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz } }, pc, elements);
  7930. } else if (use_src3) {
  7931. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz }, vk_subbuffer{ d_W, w_buf_offset, w_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7932. } else if (use_src2) {
  7933. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7934. } else if (use_src1) {
  7935. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7936. } else {
  7937. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7938. }
  7939. }
  7940. static void ggml_vk_get_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7941. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7942. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7943. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7944. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  7945. (uint32_t)ggml_nelements(src0),
  7946. (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,
  7947. (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,
  7948. (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,
  7949. 0,
  7950. 0.0f, 0.0f, 0,
  7951. }, dryrun);
  7952. }
  7953. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7954. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7955. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7956. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7957. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  7958. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  7959. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  7960. int offset = dst->op_params[3] / 4; // offset in bytes
  7961. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  7962. (uint32_t)ggml_nelements(src0),
  7963. (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,
  7964. (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,
  7965. (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,
  7966. 0,
  7967. 0.0f, 0.0f, offset,
  7968. }, dryrun);
  7969. }
  7970. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  7971. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  7972. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  7973. // Make a list of all the tensors used by the op.
  7974. // Last element of the list is the dest tensor.
  7975. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  7976. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  7977. uint32_t num_tensors = num_srcs + 1;
  7978. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  7979. tensors[0] = first_node->src[0];
  7980. tensors[1] = first_node->src[1];
  7981. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  7982. // check whether the previous result is src[0] or src[1]
  7983. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  7984. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  7985. } else {
  7986. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  7987. }
  7988. }
  7989. tensors[num_srcs] = dst;
  7990. vk_op_multi_add_push_constants pc;
  7991. pc.ne20 = (uint32_t)dst->ne[0];
  7992. pc.ne21 = (uint32_t)dst->ne[1];
  7993. pc.ne22 = (uint32_t)dst->ne[2];
  7994. pc.ne23 = (uint32_t)dst->ne[3];
  7995. for (uint32_t i = 0; i < num_tensors; ++i) {
  7996. const ggml_tensor *t = tensors[i];
  7997. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  7998. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  7999. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  8000. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  8001. }
  8002. pc.rms_partials = ctx->do_add_rms_partials;
  8003. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  8004. if (pipeline == nullptr) {
  8005. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  8006. GGML_ABORT("fatal error");
  8007. }
  8008. if (dryrun) {
  8009. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8010. return;
  8011. }
  8012. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  8013. vk_buffer buf[MAX_PARAMETER_COUNT];
  8014. size_t offset[MAX_PARAMETER_COUNT];
  8015. bool uma[MAX_PARAMETER_COUNT];
  8016. for (uint32_t i = 0; i < num_tensors; ++i) {
  8017. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8018. buf[i] = nullptr;
  8019. offset[i] = 0;
  8020. uma[i] = false;
  8021. if (ctx->device->uma) {
  8022. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8023. uma[i] = buf[i] != nullptr;
  8024. }
  8025. if (!uma[i]) {
  8026. buf[i] = buf_ctx[i]->dev_buffer;
  8027. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8028. }
  8029. GGML_ASSERT(buf[i] != nullptr);
  8030. }
  8031. // If any remaining descriptors are unused, just point them at src[0]
  8032. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  8033. buf[i] = buf[0];
  8034. offset[i] = 0;
  8035. }
  8036. if (ctx->do_add_rms_partials) {
  8037. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  8038. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  8039. }
  8040. std::array<uint32_t, 3> elements;
  8041. uint32_t ne = ggml_nelements(dst);
  8042. if (ne > 262144) {
  8043. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8044. } else if (ne > 512) {
  8045. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8046. } else {
  8047. elements = { ne, 1, 1 };
  8048. }
  8049. static_assert(MAX_PARAMETER_COUNT == 12);
  8050. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8051. {
  8052. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8053. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8054. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8055. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8056. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8057. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8058. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8059. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  8060. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  8061. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  8062. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  8063. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  8064. }, pc, elements);
  8065. }
  8066. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8067. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8068. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8069. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8070. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  8071. (uint32_t)ggml_nelements(src0),
  8072. (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,
  8073. (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,
  8074. (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,
  8075. 0,
  8076. 0.0f, 0.0f, ctx->do_add_rms_partials,
  8077. }, dryrun);
  8078. }
  8079. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8080. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8081. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8082. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8083. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  8084. (uint32_t)ggml_nelements(src0),
  8085. (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,
  8086. (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,
  8087. (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,
  8088. 0,
  8089. 0.0f, 0.0f, 0,
  8090. }, dryrun);
  8091. }
  8092. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8093. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8094. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8095. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8096. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  8097. (uint32_t)ggml_nelements(src0),
  8098. (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,
  8099. (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,
  8100. (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,
  8101. 0,
  8102. 0.0f, 0.0f, 0,
  8103. }, dryrun);
  8104. }
  8105. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8106. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8107. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8108. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8109. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  8110. (uint32_t)ggml_nelements(src0),
  8111. (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,
  8112. (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,
  8113. (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,
  8114. 0,
  8115. 0.0f, 0.0f, 0,
  8116. }, dryrun);
  8117. }
  8118. 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, bool dryrun = false) {
  8119. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8120. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8121. const uint32_t src2_type_size = ggml_type_size(src2->type);
  8122. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  8123. (uint32_t)dst->ne[0],
  8124. (uint32_t)dst->ne[1],
  8125. (uint32_t)src0->nb[1] / src0_type_size,
  8126. (uint32_t)src0->nb[2] / src0_type_size,
  8127. (uint32_t)src1->nb[1] / src1_type_size,
  8128. (uint32_t)src2->nb[1] / src2_type_size,
  8129. }, dryrun);
  8130. }
  8131. 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, bool dryrun = false) {
  8132. GGML_ASSERT(version == 6 || version == 7);
  8133. int num_srcs = version == 6 ? 6 : 7;
  8134. for (int i = 0; i < num_srcs; i++) {
  8135. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  8136. }
  8137. GGML_ASSERT(dst->buffer != nullptr);
  8138. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8139. GGML_ASSERT(pipeline != nullptr);
  8140. if (dryrun) {
  8141. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8142. return;
  8143. }
  8144. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8145. ggml_backend_vk_buffer_context * src_buf_ctxs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  8146. for (int i = 0; i < num_srcs; i++) {
  8147. src_buf_ctxs[i] = (ggml_backend_vk_buffer_context *)dst->src[i]->buffer->context;
  8148. }
  8149. vk_buffer d_D = nullptr, d_srcs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  8150. size_t dst_offset = 0, src_offsets[7] = { 0, 0, 0, 0, 0, 0, 0 };
  8151. bool dst_uma = false, srcs_uma[7] = { false, false, false, false, false, false, false };
  8152. if (ctx->device->uma) {
  8153. for (int i = 0; i < num_srcs; i++) {
  8154. ggml_vk_host_get(ctx->device, dst->src[i]->data, d_srcs[i], src_offsets[i]);
  8155. srcs_uma[i] = d_srcs[i] != nullptr;
  8156. }
  8157. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  8158. dst_uma = d_D != nullptr;
  8159. }
  8160. uint64_t src_sizes[7] = { 0, 0, 0, 0, 0, 0, 0 };
  8161. for (int i = 0; i < num_srcs; i++) {
  8162. src_sizes[i] = ggml_nbytes(dst->src[i]);
  8163. if (!srcs_uma[i]) {
  8164. d_srcs[i] = src_buf_ctxs[i]->dev_buffer;
  8165. src_offsets[i] = vk_tensor_offset(dst->src[i]) + dst->src[i]->view_offs;
  8166. }
  8167. }
  8168. const uint64_t dst_size = ggml_nbytes(dst);
  8169. if (!dst_uma) {
  8170. d_D = dst_buf_ctx->dev_buffer;
  8171. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  8172. }
  8173. std::array<uint32_t, 3> elements = {
  8174. (uint32_t)(pc.B * pc.H),
  8175. 1,
  8176. 1
  8177. };
  8178. if (version == 6) {
  8179. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  8180. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  8181. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  8182. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  8183. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  8184. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  8185. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  8186. vk_subbuffer{ d_D, dst_offset, dst_size }
  8187. }, pc, elements);
  8188. } else if (version == 7) {
  8189. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  8190. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  8191. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  8192. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  8193. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  8194. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  8195. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  8196. vk_subbuffer{ d_srcs[6], src_offsets[6], src_sizes[6] },
  8197. vk_subbuffer{ d_D, dst_offset, dst_size }
  8198. }, pc, elements);
  8199. } else {
  8200. // shouldn't happen
  8201. GGML_ASSERT(false);
  8202. }
  8203. }
  8204. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8205. const size_t seq_length = dst->src[0]->ne[2];
  8206. const size_t n_embed = dst->ne[0];
  8207. const size_t n_heads = dst->src[0]->ne[1];
  8208. const size_t n_seqs = dst->src[5]->ne[1];
  8209. ggml_vk_op_f32_wkv(
  8210. ctx, subctx, dst,
  8211. {
  8212. (uint32_t)n_seqs,
  8213. (uint32_t)seq_length,
  8214. (uint32_t)n_embed,
  8215. (uint32_t)n_heads,
  8216. },
  8217. 6,
  8218. dryrun
  8219. );
  8220. }
  8221. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8222. const size_t seq_length = dst->src[0]->ne[2];
  8223. const size_t n_embed = dst->ne[0];
  8224. const size_t n_heads = dst->src[0]->ne[1];
  8225. const size_t n_seqs = dst->src[6]->ne[1];
  8226. ggml_vk_op_f32_wkv(
  8227. ctx, subctx, dst,
  8228. {
  8229. (uint32_t)n_seqs,
  8230. (uint32_t)seq_length,
  8231. (uint32_t)n_embed,
  8232. (uint32_t)n_heads,
  8233. },
  8234. 7,
  8235. dryrun
  8236. );
  8237. }
  8238. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8239. const ggml_tensor * src0 = dst->src[0];
  8240. const ggml_tensor * src1 = dst->src[1];
  8241. const ggml_tensor * src2 = dst->src[2];
  8242. const ggml_tensor * src3 = dst->src[3];
  8243. const ggml_tensor * src4 = dst->src[4];
  8244. const ggml_tensor * src5 = dst->src[5];
  8245. GGML_ASSERT(dst->buffer != nullptr);
  8246. const uint32_t head_dim = src0->ne[1];
  8247. const uint32_t n_head = src1->ne[1];
  8248. const uint32_t n_group = src4->ne[1];
  8249. const uint32_t n_tok = src1->ne[2];
  8250. const uint32_t n_seq = src1->ne[3];
  8251. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8252. GGML_ASSERT(is_mamba2);
  8253. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8254. GGML_ASSERT(pipeline != nullptr);
  8255. if (dryrun) {
  8256. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8257. return;
  8258. }
  8259. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8260. const vk_op_ssm_scan_push_constants pc = {
  8261. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8262. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8263. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8264. (uint32_t)src3->nb[1],
  8265. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8266. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8267. (uint32_t)s_off,
  8268. n_head, head_dim, n_group, n_tok
  8269. };
  8270. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8271. ggml_backend_vk_buffer_context * src_buf_ctxs[GGML_MAX_SRC];
  8272. for (int i = 0; i < GGML_MAX_SRC && dst->src[i] != nullptr; i++) {
  8273. src_buf_ctxs[i] = (ggml_backend_vk_buffer_context *)dst->src[i]->buffer->context;
  8274. }
  8275. vk_buffer d_D = nullptr, d_srcs[GGML_MAX_SRC] = { nullptr };
  8276. size_t dst_offset = 0, src_offsets[GGML_MAX_SRC] = { 0 };
  8277. bool dst_uma = false, srcs_uma[GGML_MAX_SRC] = { false };
  8278. if (ctx->device->uma) {
  8279. for (int i = 0; i < GGML_MAX_SRC && dst->src[i] != nullptr; i++) {
  8280. ggml_vk_host_get(ctx->device, dst->src[i]->data, d_srcs[i], src_offsets[i]);
  8281. srcs_uma[i] = d_srcs[i] != nullptr;
  8282. }
  8283. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  8284. dst_uma = d_D != nullptr;
  8285. }
  8286. if (!dst_uma) {
  8287. d_D = dst_buf_ctx->dev_buffer;
  8288. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  8289. }
  8290. for (int i = 0; i < GGML_MAX_SRC && dst->src[i] != nullptr; i++) {
  8291. if (!srcs_uma[i]) {
  8292. d_srcs[i] = src_buf_ctxs[i]->dev_buffer;
  8293. src_offsets[i] = vk_tensor_offset(dst->src[i]) + dst->src[i]->view_offs;
  8294. }
  8295. }
  8296. size_t dst_size = ggml_nbytes(dst);
  8297. size_t src_sizes[GGML_MAX_SRC];
  8298. for (int i = 0; i < GGML_MAX_SRC && dst->src[i] != nullptr; i++) {
  8299. src_sizes[i] = ggml_nbytes(dst->src[i]);
  8300. }
  8301. std::array<uint32_t, 3> elements;
  8302. const int splitH = 16;
  8303. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8304. const uint32_t num_workgroups_y = n_seq;
  8305. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8306. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  8307. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  8308. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  8309. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  8310. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  8311. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  8312. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  8313. vk_subbuffer{ d_srcs[6], src_offsets[6], src_sizes[6] },
  8314. vk_subbuffer{ d_D, dst_offset, dst_size }
  8315. }, pc, elements);
  8316. }
  8317. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8318. const ggml_tensor * src0 = dst->src[0];
  8319. const ggml_tensor * src1 = dst->src[1];
  8320. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8321. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8322. (uint32_t)src1->nb[1],
  8323. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8324. (uint32_t)src1->ne[0],
  8325. (uint32_t)src0->ne[0],
  8326. (uint32_t)src0->ne[1],
  8327. (uint32_t)dst->ne[1],
  8328. (uint32_t)dst->ne[2],
  8329. }, dryrun);
  8330. }
  8331. 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, bool dryrun = false) {
  8332. const ggml_tensor * x = dst->src[0];
  8333. const ggml_tensor * g = dst->src[1];
  8334. const ggml_tensor * gm = dst->src[2];
  8335. const ggml_tensor * gv = dst->src[3];
  8336. const ggml_tensor * p = dst->src[4];
  8337. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8338. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8339. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8340. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8341. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8342. GGML_ASSERT(dst->buffer != nullptr);
  8343. GGML_ASSERT(ggml_is_contiguous(x));
  8344. GGML_ASSERT(ggml_is_contiguous(g));
  8345. GGML_ASSERT(ggml_is_contiguous(gm));
  8346. GGML_ASSERT(ggml_is_contiguous(gv));
  8347. GGML_ASSERT(ggml_is_contiguous(p));
  8348. GGML_ASSERT(ggml_are_same_shape(x, g));
  8349. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8350. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8351. GGML_ASSERT(ggml_nelements(p) == 7);
  8352. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8353. GGML_ASSERT(pipeline != nullptr);
  8354. if (dryrun) {
  8355. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8356. return;
  8357. }
  8358. ggml_backend_vk_buffer_context * x_buf_ctx = (ggml_backend_vk_buffer_context *)x->buffer->context;
  8359. ggml_backend_vk_buffer_context * g_buf_ctx = (ggml_backend_vk_buffer_context *)g->buffer->context;
  8360. ggml_backend_vk_buffer_context * gm_buf_ctx = (ggml_backend_vk_buffer_context *)gm->buffer->context;
  8361. ggml_backend_vk_buffer_context * gv_buf_ctx = (ggml_backend_vk_buffer_context *)gv->buffer->context;
  8362. ggml_backend_vk_buffer_context * p_buf_ctx = (ggml_backend_vk_buffer_context *)p->buffer->context;
  8363. vk_buffer d_X = nullptr, d_G = nullptr, d_GM = nullptr, d_GV = nullptr, d_P = nullptr;
  8364. size_t x_offset = 0, g_offset = 0, gm_offset = 0, gv_offset = 0, p_offset = 0;
  8365. bool X_uma = false, G_uma = false, GM_uma = false, GV_uma = false, P_uma = false;
  8366. if (ctx->device->uma) {
  8367. ggml_vk_host_get(ctx->device, x->data, d_X, x_offset);
  8368. ggml_vk_host_get(ctx->device, g->data, d_G, g_offset);
  8369. ggml_vk_host_get(ctx->device, gm->data, d_GM, gm_offset);
  8370. ggml_vk_host_get(ctx->device, gv->data, d_GV, gv_offset);
  8371. ggml_vk_host_get(ctx->device, p->data, d_P, p_offset);
  8372. X_uma = d_X != nullptr;
  8373. G_uma = d_G != nullptr;
  8374. GM_uma = d_GM != nullptr;
  8375. GV_uma = d_GV != nullptr;
  8376. P_uma = d_P != nullptr;
  8377. }
  8378. if (!X_uma) {
  8379. d_X = x_buf_ctx->dev_buffer;
  8380. x_offset = vk_tensor_offset(x) + x->view_offs;
  8381. }
  8382. if (!G_uma) {
  8383. d_G = g_buf_ctx->dev_buffer;
  8384. g_offset = vk_tensor_offset(g) + g->view_offs;
  8385. }
  8386. if (!GM_uma) {
  8387. d_GM = gm_buf_ctx->dev_buffer;
  8388. gm_offset = vk_tensor_offset(gm) + gm->view_offs;
  8389. }
  8390. if (!GV_uma) {
  8391. d_GV = gv_buf_ctx->dev_buffer;
  8392. gv_offset = vk_tensor_offset(gv) + gv->view_offs;
  8393. }
  8394. if (!P_uma) {
  8395. d_P = p_buf_ctx->dev_buffer;
  8396. p_offset = vk_tensor_offset(p) + p->view_offs;
  8397. }
  8398. const uint64_t x_size = ggml_nbytes(x);
  8399. const uint64_t g_size = ggml_nbytes(g);
  8400. const uint64_t gm_size = ggml_nbytes(gm);
  8401. const uint64_t gv_size = ggml_nbytes(gv);
  8402. const uint64_t p_size = ggml_nbytes(p);
  8403. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8404. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  8405. vk_subbuffer{ d_X, x_offset, x_size },
  8406. vk_subbuffer{ d_G, g_offset, g_size },
  8407. vk_subbuffer{ d_GM, gm_offset, gm_size },
  8408. vk_subbuffer{ d_GV, gv_offset, gv_size },
  8409. vk_subbuffer{ d_P, p_offset, p_size },
  8410. }, pc, elements);
  8411. }
  8412. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8413. const size_t n = ggml_nelements(dst->src[0]);
  8414. ggml_vk_op_f32_opt_step_adamw(
  8415. ctx, subctx, dst,
  8416. { (uint32_t)n, 0, 0.0f, 0.0f },
  8417. dryrun
  8418. );
  8419. }
  8420. 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, bool dryrun = false) {
  8421. const size_t n = ggml_nelements(dst->src[0]);
  8422. 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 }, dryrun);
  8423. }
  8424. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8425. int * op_params = (int *)dst->op_params;
  8426. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8427. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8428. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8429. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8430. (uint32_t)ggml_nelements(dst),
  8431. (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,
  8432. (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,
  8433. (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,
  8434. 0,
  8435. 0.0f, 0.0f, op_params[0],
  8436. }, dryrun);
  8437. }
  8438. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8439. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8440. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8441. GGML_TENSOR_UNARY_OP_LOCALS
  8442. float sf0 = (float)ne0 / ne00;
  8443. float sf1 = (float)ne1 / ne01;
  8444. float sf2 = (float)ne2 / ne02;
  8445. float sf3 = (float)ne3 / ne03;
  8446. float pixel_offset = 0.5f;
  8447. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8448. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8449. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8450. pixel_offset = 0.0f;
  8451. }
  8452. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8453. (uint32_t)ggml_nelements(dst), 0, 0,
  8454. (uint32_t)ne00, (uint32_t)ne01,
  8455. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8456. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8457. sf0, sf1, sf2, sf3, pixel_offset
  8458. }, dryrun);
  8459. }
  8460. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8461. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8462. p.param1 = ggml_get_op_params_f32(dst, 0);
  8463. p.param2 = ggml_get_op_params_f32(dst, 1);
  8464. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p), dryrun);
  8465. }
  8466. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8467. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst), dryrun);
  8468. }
  8469. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8470. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst), dryrun);
  8471. }
  8472. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8473. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst), dryrun);
  8474. }
  8475. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8476. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst), dryrun);
  8477. }
  8478. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8479. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8480. p.param1 = ggml_get_op_params_f32(dst, 0);
  8481. p.param2 = ggml_get_op_params_f32(dst, 1);
  8482. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p), dryrun);
  8483. }
  8484. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8485. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8486. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p), dryrun);
  8487. }
  8488. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8489. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8490. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8491. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8492. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8493. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8494. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8495. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8496. memcpy(&p.param1, &s01_packed, sizeof(float));
  8497. memcpy(&p.param2, &s23_packed, sizeof(float));
  8498. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p), dryrun);
  8499. }
  8500. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8501. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8502. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p), dryrun);
  8503. }
  8504. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8505. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8506. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p), dryrun);
  8507. }
  8508. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8509. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8510. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8511. // Convert from number of logical elements to 2- or 4-byte units.
  8512. ne /= ggml_blck_size(src0->type);
  8513. if ((ggml_type_size(src0->type) % 4) == 0) {
  8514. ne *= ggml_type_size(src0->type) / 4;
  8515. } else {
  8516. ne *= ggml_type_size(src0->type) / 2;
  8517. }
  8518. }
  8519. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8520. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p), dryrun);
  8521. }
  8522. 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, bool dryrun = false) {
  8523. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8524. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8525. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8526. // Skip empty skip_rows operations. For most ops the empty check at the start
  8527. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8528. // with empty srcs.
  8529. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8530. return;
  8531. }
  8532. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8533. (uint32_t)ggml_nelements(src0),
  8534. (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,
  8535. (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,
  8536. (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,
  8537. 0,
  8538. 0.0f, 0.0f, 0,
  8539. }, dryrun);
  8540. }
  8541. 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, bool dryrun = false) {
  8542. 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 }, dryrun);
  8543. }
  8544. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8545. float * op_params = (float *)dst->op_params;
  8546. 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 }, dryrun);
  8547. }
  8548. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8549. const int * int_op_params = (const int *)dst->op_params;
  8550. const float * float_op_params = (const float *)dst->op_params;
  8551. const uint32_t num_groups = int_op_params[0];
  8552. const float eps = float_op_params[1];
  8553. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8554. 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 }, dryrun);
  8555. }
  8556. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8557. const uint32_t ne = (uint32_t)node->ne[0];
  8558. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8559. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8560. return num_partials;
  8561. }
  8562. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8563. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8564. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8565. return num_bytes;
  8566. }
  8567. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, float * op_params, bool dryrun = false) {
  8568. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8569. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8570. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8571. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8572. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, {
  8573. (uint32_t)ggml_nelements(src0),
  8574. (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,
  8575. (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,
  8576. (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,
  8577. 0,
  8578. op_params[0], 0.0f, (int32_t)param3,
  8579. }, dryrun);
  8580. if (ctx->do_add_rms_partials) {
  8581. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8582. ctx->do_add_rms_partials = false;
  8583. }
  8584. }
  8585. 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, bool dryrun = false) {
  8586. float * op_params = (float *)dst->op_params;
  8587. 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 }, dryrun);
  8588. }
  8589. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8590. float * op_params = (float *)dst->op_params;
  8591. 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 }, dryrun);
  8592. }
  8593. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8594. 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 }, dryrun);
  8595. }
  8596. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8597. const float * op_params_f = (const float *)dst->op_params;
  8598. const bool swapped = (bool)dst->op_params[1];
  8599. const bool split = src1 != nullptr;
  8600. const float alpha = op_params_f[2];
  8601. const float limit = op_params_f[3];
  8602. GGML_ASSERT(ggml_is_contiguous(src0));
  8603. if (!split) {
  8604. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8605. } else {
  8606. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8607. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8608. GGML_ASSERT(src0->type == src1->type);
  8609. }
  8610. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8611. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8612. {
  8613. (uint32_t)ggml_nelements(dst),
  8614. (uint32_t)src0->ne[0],
  8615. (uint32_t)dst->ne[0],
  8616. mode,
  8617. alpha,
  8618. limit
  8619. }, dryrun);
  8620. }
  8621. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8622. int32_t * op_params = (int32_t *)dst->op_params;
  8623. 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] }, dryrun);
  8624. }
  8625. 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, bool dryrun = false) {
  8626. float * op_params = (float *)dst->op_params;
  8627. float scale = op_params[0];
  8628. float max_bias = op_params[1];
  8629. const uint32_t ncols = (uint32_t)src0->ne[0];
  8630. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8631. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8632. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8633. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8634. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8635. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8636. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8637. const uint32_t n_head_kv = src0->ne[2];
  8638. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8639. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8640. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8641. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, {
  8642. ncols,
  8643. src1 != nullptr ? nrows_y : (uint32_t)0,
  8644. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8645. ne12, ne13,
  8646. nb11, nb12, nb13,
  8647. scale, max_bias,
  8648. m0, m1,
  8649. n_head_log2,
  8650. nrows_x,
  8651. src2 != nullptr
  8652. }, dryrun);
  8653. }
  8654. 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, bool dryrun = false) {
  8655. float * op_params = (float *)dst->op_params;
  8656. 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] }, dryrun);
  8657. }
  8658. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  8659. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8660. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8661. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8662. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8663. cgraph->nodes[node_idx + 5];
  8664. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8665. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8666. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8667. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8668. const int n_experts = logits->ne[0];
  8669. const int n_rows = logits->ne[1];
  8670. const int n_expert_used = weights->ne[1];
  8671. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8672. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8673. if (dryrun) {
  8674. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8675. return;
  8676. }
  8677. ggml_backend_vk_buffer_context * logits_buf_ctx = (ggml_backend_vk_buffer_context *)logits->buffer->context;
  8678. ggml_backend_vk_buffer_context * weights_buf_ctx = (ggml_backend_vk_buffer_context *)weights->buffer->context;
  8679. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  8680. vk_buffer d_logits = nullptr;
  8681. size_t logits_buf_offset = 0;
  8682. vk_buffer d_weights = nullptr;
  8683. size_t weights_buf_offset = 0;
  8684. vk_buffer d_ids = nullptr;
  8685. size_t ids_buf_offset = 0;
  8686. bool logits_uma = false;
  8687. bool weights_uma = false;
  8688. bool ids_uma = false;
  8689. if (ctx->device->uma) {
  8690. ggml_vk_host_get(ctx->device, logits->data, d_logits, logits_buf_offset);
  8691. ggml_vk_host_get(ctx->device, weights->data, d_weights, weights_buf_offset);
  8692. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  8693. logits_uma = d_logits != nullptr;
  8694. weights_uma = d_weights != nullptr;
  8695. ids_uma = d_ids != nullptr;
  8696. }
  8697. if (!logits_uma) {
  8698. d_logits = logits_buf_ctx->dev_buffer;
  8699. logits_buf_offset = vk_tensor_offset(logits) + logits->view_offs;
  8700. GGML_ASSERT(d_logits != nullptr);
  8701. }
  8702. if (!weights_uma) {
  8703. d_weights = weights_buf_ctx->dev_buffer;
  8704. weights_buf_offset = vk_tensor_offset(weights) + weights->view_offs;
  8705. GGML_ASSERT(d_weights != nullptr);
  8706. }
  8707. if (!ids_uma) {
  8708. d_ids = ids_buf_ctx->dev_buffer;
  8709. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  8710. GGML_ASSERT(d_ids != nullptr);
  8711. }
  8712. vk_op_topk_moe_push_constants pc {};
  8713. pc.n_rows = n_rows;
  8714. pc.n_expert_used = n_expert_used;
  8715. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8716. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8717. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8718. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8719. }
  8720. GGML_ASSERT(n_expert_used <= n_experts);
  8721. const uint32_t rows_per_block = 4;
  8722. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8723. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8724. {
  8725. ggml_vk_subbuffer(ctx, d_logits, logits_buf_offset),
  8726. ggml_vk_subbuffer(ctx, d_weights, weights_buf_offset),
  8727. ggml_vk_subbuffer(ctx, d_ids, ids_buf_offset),
  8728. }, pc, elements);
  8729. }
  8730. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop, bool dryrun = false) {
  8731. ggml_tensor * dst = cgraph->nodes[node_idx];
  8732. const ggml_tensor * src0 = dst->src[0];
  8733. const ggml_tensor * src1 = dst->src[1];
  8734. const ggml_tensor * src2 = dst->src[2];
  8735. const ggml_tensor * src3 = nullptr;
  8736. const int n_dims = ((int32_t *) dst->op_params)[1];
  8737. const int mode = ((int32_t *) dst->op_params)[2];
  8738. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8739. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8740. const float freq_base = ((float *) dst->op_params)[5];
  8741. const float freq_scale = ((float *) dst->op_params)[6];
  8742. const float ext_factor = ((float *) dst->op_params)[7];
  8743. const float attn_factor = ((float *) dst->op_params)[8];
  8744. const float beta_fast = ((float *) dst->op_params)[9];
  8745. const float beta_slow = ((float *) dst->op_params)[10];
  8746. int sections[4] {};
  8747. if (mode & GGML_ROPE_TYPE_MROPE) {
  8748. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8749. }
  8750. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8751. float corr_dims[2];
  8752. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8753. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8754. uint32_t s1 = src0->nb[1] / ggml_type_size(src0->type);
  8755. uint32_t s2 = src0->nb[2] / ggml_type_size(src0->type);
  8756. uint32_t set_rows_stride = 0;
  8757. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8758. // and overrides the dst and sets src3=row_indices
  8759. if (ctx->num_additional_fused_ops > 0) {
  8760. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8761. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8762. dst = cgraph->nodes[node_idx + 2];
  8763. }
  8764. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE, {
  8765. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8766. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8767. src2 != nullptr, (uint32_t)src0->ne[2], s1, s2,
  8768. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8769. }, dryrun);
  8770. }
  8771. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8772. int32_t * op_params = (int32_t *)dst->op_params;
  8773. uint32_t ncols = src0->ne[0];
  8774. uint32_t nrows = ggml_nrows(src0);
  8775. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  8776. ncols,
  8777. nrows,
  8778. op_params[0],
  8779. }, dryrun);
  8780. }
  8781. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8782. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  8783. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p, dryrun);
  8784. }
  8785. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8786. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8787. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p, dryrun);
  8788. }
  8789. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8790. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8791. p.weight = 1.0f / (float)src0->ne[0];
  8792. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p, dryrun);
  8793. }
  8794. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8795. 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 }, dryrun);
  8796. }
  8797. 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, bool dryrun = false) {
  8798. 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 }, dryrun);
  8799. }
  8800. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8801. const int32_t s0 = dst->op_params[0];
  8802. const int32_t s1 = dst->op_params[1];
  8803. const int32_t p0 = dst->op_params[2];
  8804. const int32_t p1 = dst->op_params[3];
  8805. const int32_t d0 = dst->op_params[4];
  8806. const int32_t d1 = dst->op_params[5];
  8807. const bool is_2D = dst->op_params[6] == 1;
  8808. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8809. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  8810. const uint32_t IW = src1->ne[0];
  8811. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8812. const uint32_t KW = src0->ne[0];
  8813. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8814. const uint32_t OW = dst->ne[1];
  8815. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  8816. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  8817. const uint32_t pelements = OW * KW * KH;
  8818. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8819. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8820. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8821. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  8822. dst_addr,
  8823. batch_offset, offset_delta,
  8824. IC, IW, IH, OW, OH, KW, KH,
  8825. pelements,
  8826. IC * KH * KW,
  8827. s0, s1, p0, p1, d0, d1,
  8828. }, dryrun);
  8829. }
  8830. 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, bool dryrun = false) {
  8831. GGML_TENSOR_BINARY_OP_LOCALS
  8832. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  8833. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  8834. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  8835. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  8836. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  8837. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  8838. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  8839. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  8840. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  8841. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  8842. const int64_t N = ne13 / IC;
  8843. const int64_t ID = ne12;
  8844. const int64_t IH = ne11;
  8845. const int64_t IW = ne10;
  8846. const int64_t KD = ne02;
  8847. const int64_t KH = ne01;
  8848. const int64_t KW = ne00;
  8849. const int64_t OD = ne3 / N;
  8850. const int64_t OH = ne2;
  8851. const int64_t OW = ne1;
  8852. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8853. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8854. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8855. vk_op_im2col_3d_push_constants pc {};
  8856. pc.dst_addr = dst_addr;
  8857. pc.nb10 = nb10 / ggml_type_size(src1->type);
  8858. pc.nb11 = nb11 / ggml_type_size(src1->type);
  8859. pc.nb12 = nb12 / ggml_type_size(src1->type);
  8860. pc.nb13 = nb13 / ggml_type_size(src1->type);
  8861. pc.s0 = s0;
  8862. pc.s1 = s1;
  8863. pc.s2 = s2;
  8864. pc.p0 = p0;
  8865. pc.p1 = p1;
  8866. pc.p2 = p2;
  8867. pc.d0 = d0;
  8868. pc.d1 = d1;
  8869. pc.d2 = d2;
  8870. pc.IW = IW;
  8871. pc.IH = IH;
  8872. pc.ID = ID;
  8873. pc.IC = IC;
  8874. pc.KW = KW;
  8875. pc.OH = OH;
  8876. pc.KD_KH_KW = KD*KH*KW;
  8877. pc.KH_KW = KH*KW;
  8878. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  8879. pc.N_OD_OH = N*OD*OH;
  8880. pc.OD_OH = OD*OH;
  8881. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  8882. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  8883. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  8884. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc), dryrun);
  8885. }
  8886. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8887. const uint32_t dim = dst->op_params[0];
  8888. const uint32_t max_period = dst->op_params[1];
  8889. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  8890. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  8891. nb1, dim, max_period,
  8892. }, dryrun);
  8893. }
  8894. 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, bool dryrun = false) {
  8895. // src0: (K, Cout, Cin, 1) -- kernel
  8896. // src1: (L, Cin, 1, 1) -- input
  8897. // dst: (*, Cout, 1, 1)
  8898. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  8899. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8900. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  8901. GGML_TENSOR_BINARY_OP_LOCALS
  8902. GGML_ASSERT(nb00 == sizeof(float));
  8903. GGML_ASSERT(nb10 == sizeof(float));
  8904. const int32_t s0 = dst->op_params[0];
  8905. vk_op_conv_transpose_1d_push_constants p{};
  8906. p.Cout = static_cast<uint32_t>(ne01);
  8907. p.Cin = static_cast<uint32_t>(ne02);
  8908. p.K = static_cast<uint32_t>(ne00);
  8909. p.L = static_cast<uint32_t>(ne10);
  8910. p.KL = static_cast<uint32_t>(ne0);
  8911. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8912. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8913. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8914. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8915. p.s0 = static_cast<uint32_t>(s0);
  8916. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p), dryrun);
  8917. }
  8918. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8919. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  8920. const int32_t k1 = dst->op_params[1];
  8921. const int32_t k0 = dst->op_params[2];
  8922. const int32_t s1 = dst->op_params[3];
  8923. const int32_t s0 = dst->op_params[4];
  8924. const int32_t p1 = dst->op_params[5];
  8925. const int32_t p0 = dst->op_params[6];
  8926. const uint32_t IH = src0->ne[1];
  8927. const uint32_t IW = src0->ne[0];
  8928. const uint32_t N = dst->ne[3];
  8929. const uint32_t OC = dst->ne[2];
  8930. const uint32_t OH = dst->ne[1];
  8931. const uint32_t OW = dst->ne[0];
  8932. const uint32_t parallel_elements = N * OC * OH * OW;
  8933. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  8934. IW, IH, OW, OH, OC,
  8935. parallel_elements,
  8936. op,
  8937. k0, k1, s0, s1, p0, p1,
  8938. }, dryrun);
  8939. }
  8940. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8941. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8942. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8943. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8944. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8945. GGML_TENSOR_BINARY_OP_LOCALS
  8946. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8947. GGML_ASSERT(nb10 == sizeof(float));
  8948. GGML_ASSERT(nb0 == sizeof(float));
  8949. vk_op_conv2d_push_constants p{};
  8950. p.Cout = static_cast<uint32_t>(ne03);
  8951. p.Cin = static_cast<uint32_t>(ne02);
  8952. p.N = static_cast<uint32_t>(ne13);
  8953. p.KW = static_cast<uint32_t>(ne00);
  8954. p.KH = static_cast<uint32_t>(ne01);
  8955. p.W = static_cast<uint32_t>(ne10);
  8956. p.H = static_cast<uint32_t>(ne11);
  8957. p.OW = static_cast<uint32_t>(ne0);
  8958. p.OH = static_cast<uint32_t>(ne1);
  8959. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8960. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  8961. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  8962. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  8963. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  8964. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  8965. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8966. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8967. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8968. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8969. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8970. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8971. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8972. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8973. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8974. GGML_ASSERT(ne03 == ne2);
  8975. GGML_ASSERT(ne02 == ne12);
  8976. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D, std::move(p), dryrun);
  8977. }
  8978. static void ggml_vk_conv_transpose_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8979. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8980. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8981. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8982. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8983. GGML_TENSOR_BINARY_OP_LOCALS
  8984. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8985. GGML_ASSERT(nb10 == sizeof(float));
  8986. GGML_ASSERT(nb0 == sizeof(float));
  8987. vk_op_conv_transpose_2d_push_constants p{};
  8988. p.Cout = static_cast<uint32_t>(ne02);
  8989. p.Cin = static_cast<uint32_t>(ne03);
  8990. p.N = static_cast<uint32_t>(ne13);
  8991. p.KW = static_cast<uint32_t>(ne00);
  8992. p.KH = static_cast<uint32_t>(ne01);
  8993. p.W = static_cast<uint32_t>(ne10);
  8994. p.H = static_cast<uint32_t>(ne11);
  8995. p.OW = static_cast<uint32_t>(ne0);
  8996. p.OH = static_cast<uint32_t>(ne1);
  8997. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8998. p.s1 = static_cast<uint32_t>(dst->op_params[0]);
  8999. p.p0 = 0;
  9000. p.p1 = 0;
  9001. p.d0 = 1;
  9002. p.d1 = 1;
  9003. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9004. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9005. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  9006. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9007. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  9008. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  9009. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9010. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  9011. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  9012. GGML_ASSERT(ne02 == ne2);
  9013. GGML_ASSERT(ne03 == ne12);
  9014. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_2D, std::move(p), dryrun);
  9015. }
  9016. 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, bool dryrun = false) {
  9017. vk_op_conv2d_dw_push_constants p{};
  9018. p.ne = ggml_nelements(dst);
  9019. p.channels = dst->ne[2];
  9020. p.batches = dst->ne[3];
  9021. p.dst_w = dst->ne[0];
  9022. p.dst_h = dst->ne[1];
  9023. p.src_w = src1->ne[0];
  9024. p.src_h = src1->ne[1];
  9025. p.knl_w = src0->ne[0];
  9026. p.knl_h = src0->ne[1];
  9027. p.stride_x = dst->op_params[0];
  9028. p.stride_y = dst->op_params[1];
  9029. p.pad_x = dst->op_params[2];
  9030. p.pad_y = dst->op_params[3];
  9031. p.dilation_x = dst->op_params[4];
  9032. p.dilation_y = dst->op_params[5];
  9033. GGML_ASSERT(src0->ne[3] == p.channels);
  9034. GGML_ASSERT(src1->ne[3] == p.batches);
  9035. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p), dryrun);
  9036. }
  9037. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  9038. const float * op_params = (const float *)dst->op_params;
  9039. 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 }, dryrun);
  9040. }
  9041. #ifdef GGML_VULKAN_RUN_TESTS
  9042. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  9043. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  9044. return;
  9045. }
  9046. i0 = std::max(i0, 5);
  9047. i1 = std::max(i1, 5);
  9048. i2 = std::max(i2, 0);
  9049. fprintf(stderr, " ");
  9050. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9051. fprintf(stderr, "%7d ", idx1);
  9052. }
  9053. fprintf(stderr, "\n");
  9054. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9055. fprintf(stderr, "%7d: ", idx0);
  9056. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9057. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  9058. float val;
  9059. if (type == GGML_TYPE_F32) {
  9060. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  9061. } else if (type == GGML_TYPE_F16) {
  9062. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  9063. } else {
  9064. GGML_ABORT("fatal error");
  9065. }
  9066. fprintf(stderr, "% 7.2f ", val);
  9067. } else {
  9068. fprintf(stderr, " ");
  9069. }
  9070. }
  9071. fprintf(stderr, "\n");
  9072. }
  9073. }
  9074. template <typename X_TYPE, typename Y_TYPE>
  9075. 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) {
  9076. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  9077. const size_t x_ne = m * k * batch;
  9078. const size_t y_ne = k * n * batch;
  9079. const size_t d_ne = m * n * batch;
  9080. vk_pipeline p;
  9081. std::string shname;
  9082. if (shader_size == 0) {
  9083. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9084. p = ctx->device->pipeline_matmul_f32->a_s;
  9085. shname = "F32_ALIGNED_S";
  9086. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9087. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  9088. shname = "F32_F16_ALIGNED_S";
  9089. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9090. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  9091. shname = "F16_F32_ALIGNED_S";
  9092. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9093. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  9094. shname = "F16_ALIGNED_S";
  9095. } else {
  9096. GGML_ABORT("fatal error");
  9097. }
  9098. } else if (shader_size == 1) {
  9099. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9100. p = ctx->device->pipeline_matmul_f32->a_m;
  9101. shname = "F32_ALIGNED_M";
  9102. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9103. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  9104. shname = "F32_F16_ALIGNED_M";
  9105. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9106. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  9107. shname = "F16_F32_ALIGNED_M";
  9108. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9109. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  9110. shname = "F16_ALIGNED_M";
  9111. } else {
  9112. GGML_ABORT("fatal error");
  9113. }
  9114. } else if (shader_size == 2) {
  9115. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9116. p = ctx->device->pipeline_matmul_f32->a_l;
  9117. shname = "F32_ALIGNED_L";
  9118. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9119. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  9120. shname = "F32_F16_ALIGNED_L";
  9121. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9122. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  9123. shname = "F16_F32_ALIGNED_L";
  9124. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9125. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  9126. shname = "F16_ALIGNED_L";
  9127. } else {
  9128. GGML_ABORT("fatal error");
  9129. }
  9130. } else {
  9131. GGML_ASSERT(0);
  9132. }
  9133. const size_t kpad = ggml_vk_align_size(k, p->align);
  9134. if (k != kpad) {
  9135. if (shader_size == 0) {
  9136. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9137. p = ctx->device->pipeline_matmul_f32->s;
  9138. shname = "F32_S";
  9139. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9140. p = ctx->device->pipeline_matmul_f32_f16->s;
  9141. shname = "F32_F16_S";
  9142. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9143. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  9144. shname = "F16_F32_S";
  9145. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9146. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  9147. shname = "F16_S";
  9148. }
  9149. } else if (shader_size == 1) {
  9150. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9151. p = ctx->device->pipeline_matmul_f32->m;
  9152. shname = "F32_M";
  9153. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9154. p = ctx->device->pipeline_matmul_f32_f16->m;
  9155. shname = "F32_F16_M";
  9156. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9157. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  9158. shname = "F16_F32_M";
  9159. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9160. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  9161. shname = "F16_M";
  9162. }
  9163. } else if (shader_size == 2) {
  9164. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9165. p = ctx->device->pipeline_matmul_f32->l;
  9166. shname = "F32_L";
  9167. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9168. p = ctx->device->pipeline_matmul_f32_f16->l;
  9169. shname = "F32_F16_L";
  9170. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9171. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  9172. shname = "F16_F32_L";
  9173. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9174. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  9175. shname = "F16_L";
  9176. }
  9177. }
  9178. }
  9179. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9180. if (split_k > 1) {
  9181. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9182. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9183. // Resize buffer
  9184. if (ctx->prealloc_split_k != nullptr) {
  9185. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9186. }
  9187. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9188. }
  9189. }
  9190. if (ctx->device->need_compiles) {
  9191. ggml_vk_load_shaders(ctx->device);
  9192. }
  9193. ggml_pipeline_allocate_descriptor_sets(ctx);
  9194. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9195. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9196. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9197. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9198. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9199. float* d = (float *) malloc(sizeof(float) * d_ne);
  9200. for (size_t i = 0; i < x_ne; i++) {
  9201. if (std::is_same<float, X_TYPE>()) {
  9202. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9203. // x[i] = 1.0f;
  9204. // x[i] = i + 1;
  9205. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9206. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9207. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9208. // x[i] = ggml_fp32_to_fp16(1.0f);
  9209. // x[i] = ggml_fp32_to_fp16(i + 1);
  9210. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9211. } else {
  9212. GGML_ABORT("fatal error");
  9213. }
  9214. }
  9215. for (size_t i = 0; i < y_ne; i++) {
  9216. if (std::is_same<float, Y_TYPE>()) {
  9217. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9218. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9219. // y[i] = i + 1;
  9220. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9221. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9222. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9223. // y[i] = ggml_fp32_to_fp16(i + 1);
  9224. } else {
  9225. GGML_ABORT("fatal error");
  9226. }
  9227. }
  9228. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9229. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9230. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9231. ggml_vk_ctx_begin(ctx->device, subctx);
  9232. for (size_t i = 0; i < num_it; i++) {
  9233. ggml_vk_matmul(
  9234. 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),
  9235. m, n, k,
  9236. k, k, m, k*m, k*n, m*n,
  9237. split_k, batch, batch, batch, 1, 1, n
  9238. );
  9239. }
  9240. ggml_vk_ctx_end(subctx);
  9241. auto begin = std::chrono::high_resolution_clock::now();
  9242. ggml_vk_submit(subctx, ctx->fence);
  9243. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9244. ctx->device->device.resetFences({ ctx->fence });
  9245. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9246. auto end = std::chrono::high_resolution_clock::now();
  9247. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9248. // copy dst to host
  9249. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9250. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9251. ggml_init_params iparams = {
  9252. /*.mem_size =*/ 1024*1024*1024,
  9253. /*.mem_buffer =*/ NULL,
  9254. /*.no_alloc =*/ true,
  9255. };
  9256. ggml_context * ggml_ctx = ggml_init(iparams);
  9257. ggml_type src0_type;
  9258. ggml_type src1_type;
  9259. if (std::is_same<float, X_TYPE>()) {
  9260. src0_type = GGML_TYPE_F32;
  9261. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9262. src0_type = GGML_TYPE_F16;
  9263. } else {
  9264. GGML_ABORT("fatal error");
  9265. }
  9266. if (std::is_same<float, Y_TYPE>()) {
  9267. src1_type = GGML_TYPE_F32;
  9268. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9269. src1_type = GGML_TYPE_F16;
  9270. } else {
  9271. GGML_ABORT("fatal error");
  9272. }
  9273. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9274. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9275. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9276. src0_ggml->data = x;
  9277. src1_ggml->data = y;
  9278. tensor_ggml->data = d_chk;
  9279. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9280. ggml_build_forward_expand(cgraph, tensor_ggml);
  9281. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9282. ggml_free(ggml_ctx);
  9283. double avg_err = 0.0;
  9284. int first_err_n = -1;
  9285. int first_err_m = -1;
  9286. int first_err_b = -1;
  9287. for (size_t i = 0; i < m*n*batch; i++) {
  9288. double err = std::fabs(d[i] - d_chk[i]);
  9289. avg_err += err;
  9290. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9291. first_err_b = i / (m * n);
  9292. first_err_n = (i % (m * n)) / m;
  9293. first_err_m = (i % (m * n)) % m;
  9294. }
  9295. }
  9296. avg_err /= m * n;
  9297. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9298. 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;
  9299. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9300. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9301. std::cerr << "Actual result: " << std::endl << std::endl;
  9302. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9303. std::cerr << "Expected result: " << std::endl << std::endl;
  9304. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9305. if (split_k > 1) {
  9306. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9307. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9308. std::cerr << "d_buf0: " << std::endl << std::endl;
  9309. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9310. std::cerr << "d_buf1: " << std::endl << std::endl;
  9311. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9312. std::cerr << "d_buf2: " << std::endl << std::endl;
  9313. 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);
  9314. std::cerr << "d_buf3: " << std::endl << std::endl;
  9315. 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);
  9316. free(split_k_buf);
  9317. }
  9318. }
  9319. free(d_chk);
  9320. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9321. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9322. ggml_vk_destroy_buffer(d_X);
  9323. ggml_vk_destroy_buffer(d_Y);
  9324. ggml_vk_destroy_buffer(d_D);
  9325. free(x);
  9326. free(y);
  9327. free(d);
  9328. }
  9329. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9330. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9331. return;
  9332. }
  9333. i0 = std::max(i0, 5);
  9334. i1 = std::max(i1, 5);
  9335. i2 = std::max(i2, 0);
  9336. i3 = std::max(i3, 0);
  9337. fprintf(stderr, " ");
  9338. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9339. fprintf(stderr, "%7d ", idx1);
  9340. }
  9341. fprintf(stderr, "\n");
  9342. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9343. fprintf(stderr, "%7d: ", idx0);
  9344. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9345. 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]) {
  9346. float val;
  9347. if (tensor->type == GGML_TYPE_F32) {
  9348. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9349. } else if (tensor->type == GGML_TYPE_F16) {
  9350. 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]));
  9351. } else {
  9352. GGML_ABORT("fatal error");
  9353. }
  9354. fprintf(stderr, "% 7.2f ", val);
  9355. } else {
  9356. fprintf(stderr, " ");
  9357. }
  9358. }
  9359. fprintf(stderr, "\n");
  9360. }
  9361. }
  9362. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9363. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9364. }
  9365. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9366. if (quant == GGML_TYPE_F32) {
  9367. memcpy(to, from, sizeof(float) * ne);
  9368. return;
  9369. }
  9370. const auto * tt = ggml_get_type_traits(quant);
  9371. ggml_to_float_t dequant_fn = tt->to_float;
  9372. dequant_fn(from, to, ne);
  9373. }
  9374. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9375. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9376. const size_t x_sz = sizeof(float) * ne;
  9377. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9378. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9379. float * x = (float *) malloc(x_sz);
  9380. void * qx = malloc(qx_sz);
  9381. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9382. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9383. float * x_ref = (float *) malloc(x_sz);
  9384. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9385. for (size_t i = 0; i < ne; i++) {
  9386. x[i] = rand() / (float)RAND_MAX;
  9387. }
  9388. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9389. ggml_vk_quantize_data(x, qx, ne, quant);
  9390. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9391. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9392. if (ctx->device->need_compiles) {
  9393. ggml_vk_load_shaders(ctx->device);
  9394. }
  9395. ggml_pipeline_allocate_descriptor_sets(ctx);
  9396. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9397. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9398. ggml_vk_ctx_begin(ctx->device, subctx);
  9399. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9400. 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});
  9401. ggml_vk_ctx_end(subctx);
  9402. auto begin = std::chrono::high_resolution_clock::now();
  9403. ggml_vk_submit(subctx, ctx->fence);
  9404. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9405. ctx->device->device.resetFences({ ctx->fence });
  9406. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9407. auto end = std::chrono::high_resolution_clock::now();
  9408. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9409. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9410. int first_err = -1;
  9411. double avg_err = 0.0;
  9412. for (size_t i = 0; i < ne; i++) {
  9413. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9414. avg_err += error;
  9415. if (first_err < 0 && error > 0.05) {
  9416. first_err = i;
  9417. }
  9418. }
  9419. avg_err /= ne;
  9420. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9421. if (avg_err > 0.1) {
  9422. std::cerr << "first_error = " << first_err << std::endl;
  9423. std::cerr << "Actual result: " << std::endl << std::endl;
  9424. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9425. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9426. }
  9427. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9428. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9429. std::cerr << x_ref[i] << ", ";
  9430. }
  9431. std::cerr << std::endl;
  9432. }
  9433. ggml_vk_destroy_buffer(x_buf);
  9434. ggml_vk_destroy_buffer(qx_buf);
  9435. free(x);
  9436. free(qx);
  9437. free(x_ref);
  9438. free(x_chk);
  9439. }
  9440. // This does not work without ggml q8_1 quantization support
  9441. //
  9442. // typedef uint16_t ggml_half;
  9443. // typedef uint32_t ggml_half2;
  9444. //
  9445. // #define QK8_1 32
  9446. // typedef struct {
  9447. // union {
  9448. // struct {
  9449. // ggml_half d; // delta
  9450. // ggml_half s; // d * sum(qs[i])
  9451. // } GGML_COMMON_AGGR_S;
  9452. // ggml_half2 ds;
  9453. // } GGML_COMMON_AGGR_U;
  9454. // int8_t qs[QK8_1]; // quants
  9455. // } block_q8_1;
  9456. //
  9457. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9458. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9459. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9460. //
  9461. // const size_t x_sz = sizeof(float) * ne;
  9462. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9463. // float * x = (float *) malloc(x_sz);
  9464. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9465. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9466. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9467. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9468. //
  9469. // for (size_t i = 0; i < ne; i++) {
  9470. // x[i] = rand() / (float)RAND_MAX;
  9471. // }
  9472. //
  9473. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9474. //
  9475. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9476. //
  9477. // if (ctx->device->need_compiles) {
  9478. // ggml_vk_load_shaders(ctx->device);
  9479. // }
  9480. //
  9481. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9482. //
  9483. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9484. //
  9485. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9486. // ggml_vk_ctx_begin(ctx->device, subctx);
  9487. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9488. // ggml_vk_ctx_end(subctx);
  9489. //
  9490. // auto begin = std::chrono::high_resolution_clock::now();
  9491. //
  9492. // ggml_vk_submit(subctx, ctx->fence);
  9493. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9494. // ctx->device->device.resetFences({ ctx->fence });
  9495. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9496. //
  9497. // auto end = std::chrono::high_resolution_clock::now();
  9498. //
  9499. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9500. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9501. //
  9502. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9503. //
  9504. // int first_err = -1;
  9505. //
  9506. // for (size_t i = 0; i < ne / 32; i++) {
  9507. // 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));
  9508. //
  9509. // if (first_err < 0 && error > 0.1) {
  9510. // first_err = i;
  9511. // }
  9512. //
  9513. // 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));
  9514. //
  9515. // if (first_err < 0 && error > 0.1) {
  9516. // first_err = i;
  9517. // }
  9518. //
  9519. // for (size_t j = 0; j < 32; j++) {
  9520. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9521. //
  9522. // if (first_err < 0 && error > 1) {
  9523. // first_err = i;
  9524. // }
  9525. // }
  9526. // }
  9527. //
  9528. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9529. //
  9530. // if (first_err != -1) {
  9531. // std::cerr << "first_error = " << first_err << std::endl;
  9532. // std::cerr << "Actual result: " << std::endl << std::endl;
  9533. // 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) << " ";
  9534. // for (size_t j = 0; j < 32; j++) {
  9535. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9536. // }
  9537. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9538. // 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) << " ";
  9539. // for (size_t j = 0; j < 32; j++) {
  9540. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9541. // }
  9542. // std::cerr << std::endl;
  9543. // }
  9544. //
  9545. // ggml_vk_destroy_buffer(x_buf);
  9546. // ggml_vk_destroy_buffer(qx_buf);
  9547. //
  9548. // free(x);
  9549. // free(qx);
  9550. // free(qx_res);
  9551. // }
  9552. 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) {
  9553. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9554. const size_t x_ne = m * k * batch;
  9555. const size_t y_ne = k * n * batch;
  9556. const size_t d_ne = m * n * batch;
  9557. vk_matmul_pipeline2 * pipelines;
  9558. if (mmq) {
  9559. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9560. } else {
  9561. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9562. }
  9563. const bool fp16acc = ctx->device->fp16;
  9564. vk_pipeline p;
  9565. std::string shname;
  9566. if (shader_size == 0) {
  9567. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9568. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9569. } else if (shader_size == 1) {
  9570. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9571. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9572. } else if (shader_size == 2) {
  9573. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9574. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9575. } else {
  9576. GGML_ASSERT(0);
  9577. }
  9578. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9579. if (mmq || k != kpad) {
  9580. if (shader_size == 0) {
  9581. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9582. shname = std::string(ggml_type_name(quant)) + "_S";
  9583. } else if (shader_size == 1) {
  9584. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9585. shname = std::string(ggml_type_name(quant)) + "_M";
  9586. } else if (shader_size == 2) {
  9587. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9588. shname = std::string(ggml_type_name(quant)) + "_L";
  9589. } else {
  9590. GGML_ASSERT(0);
  9591. }
  9592. }
  9593. if (p == nullptr) {
  9594. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9595. return;
  9596. }
  9597. const size_t x_sz = sizeof(float) * x_ne;
  9598. const size_t y_sz = sizeof(float) * y_ne;
  9599. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9600. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9601. const size_t d_sz = sizeof(float) * d_ne;
  9602. float * x = (float *) malloc(x_sz);
  9603. float * y = (float *) malloc(y_sz);
  9604. void * qx = malloc(qx_sz);
  9605. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9606. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9607. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9608. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9609. float * d = (float *) malloc(d_sz);
  9610. float * d_chk = (float *) malloc(d_sz);
  9611. for (size_t i = 0; i < x_ne; i++) {
  9612. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9613. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9614. // x[i] = i % k;
  9615. }
  9616. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9617. for (size_t i = 0; i < y_ne; i++) {
  9618. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9619. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9620. // y[i] = i % k;
  9621. }
  9622. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9623. if (split_k > 1) {
  9624. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9625. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9626. // Resize buffer
  9627. if (ctx->prealloc_split_k != nullptr) {
  9628. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9629. }
  9630. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9631. }
  9632. }
  9633. if (mmq) {
  9634. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9635. }
  9636. if (ctx->device->need_compiles) {
  9637. ggml_vk_load_shaders(ctx->device);
  9638. }
  9639. ggml_pipeline_allocate_descriptor_sets(ctx);
  9640. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9641. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9642. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9643. ggml_vk_ctx_begin(ctx->device, subctx);
  9644. if (mmq) {
  9645. for (size_t i = 0; i < num_it; i++) {
  9646. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9647. ggml_vk_matmul(
  9648. 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 },
  9649. m, n, k,
  9650. k, k, m, k*m, k*n, m*n,
  9651. split_k, batch, batch, batch, 1, 1, n
  9652. );
  9653. }
  9654. } else {
  9655. for (size_t i = 0; i < num_it; i++) {
  9656. ggml_vk_matmul(
  9657. 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 },
  9658. m, n, k,
  9659. k, k, m, k*m, k*n, m*n,
  9660. split_k, batch, batch, batch, 1, 1, n
  9661. );
  9662. }
  9663. }
  9664. ggml_vk_ctx_end(subctx);
  9665. auto begin = std::chrono::high_resolution_clock::now();
  9666. ggml_vk_submit(subctx, ctx->fence);
  9667. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9668. ctx->device->device.resetFences({ ctx->fence });
  9669. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9670. auto end = std::chrono::high_resolution_clock::now();
  9671. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9672. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9673. ggml_init_params iparams = {
  9674. /*.mem_size =*/ 1024*1024*1024,
  9675. /*.mem_buffer =*/ NULL,
  9676. /*.no_alloc =*/ true,
  9677. };
  9678. ggml_context * ggml_ctx = ggml_init(iparams);
  9679. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9680. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9681. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9682. src0_ggml->data = qx;
  9683. src1_ggml->data = y;
  9684. tensor_ggml->data = d_chk;
  9685. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9686. ggml_build_forward_expand(cgraph, tensor_ggml);
  9687. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9688. ggml_free(ggml_ctx);
  9689. double avg_err = 0.0;
  9690. int first_err_n = -1;
  9691. int first_err_m = -1;
  9692. int first_err_b = -1;
  9693. for (size_t i = 0; i < m*n*batch; i++) {
  9694. double err = std::fabs(d[i] - d_chk[i]);
  9695. avg_err += err;
  9696. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9697. first_err_b = i / (m * n);
  9698. first_err_n = (i % (m * n)) / m;
  9699. first_err_m = (i % (m * n)) % m;
  9700. }
  9701. }
  9702. avg_err /= m * n;
  9703. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9704. std::cerr << "TEST dequant matmul " << shname;
  9705. if (mmq) {
  9706. std::cerr << " mmq";
  9707. }
  9708. 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;
  9709. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9710. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9711. std::cerr << "Actual result: " << std::endl << std::endl;
  9712. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9713. std::cerr << std::endl;
  9714. std::cerr << "Expected result: " << std::endl << std::endl;
  9715. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9716. std::cerr << "src0: " << std::endl << std::endl;
  9717. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9718. std::cerr << std::endl;
  9719. std::cerr << "src1: " << std::endl << std::endl;
  9720. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9721. if (split_k > 1) {
  9722. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9723. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9724. std::cerr << "d_buf0: " << std::endl << std::endl;
  9725. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9726. std::cerr << "d_buf1: " << std::endl << std::endl;
  9727. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9728. std::cerr << "d_buf2: " << std::endl << std::endl;
  9729. 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);
  9730. std::cerr << "d_buf3: " << std::endl << std::endl;
  9731. 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);
  9732. free(split_k_buf);
  9733. }
  9734. }
  9735. ggml_vk_destroy_buffer(qx_buf);
  9736. ggml_vk_destroy_buffer(y_buf);
  9737. ggml_vk_destroy_buffer(qy_buf);
  9738. ggml_vk_destroy_buffer(d_buf);
  9739. free(x);
  9740. free(qx);
  9741. free(y);
  9742. free(d);
  9743. free(d_chk);
  9744. }
  9745. #endif
  9746. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  9747. #if defined(GGML_VULKAN_RUN_TESTS)
  9748. const std::vector<size_t> vals {
  9749. 512, 512, 128,
  9750. 128, 512, 512,
  9751. 4096, 512, 4096,
  9752. 11008, 512, 4096,
  9753. 4096, 512, 11008,
  9754. 32000, 512, 4096,
  9755. 8, 8, 8,
  9756. 100, 46, 576,
  9757. 623, 111, 128,
  9758. 100, 46, 558,
  9759. 512, 1, 256,
  9760. 128, 110, 622,
  9761. 511, 511, 127,
  9762. 511, 511, 7,
  9763. 511, 511, 17,
  9764. 49, 49, 128,
  9765. 128, 49, 49,
  9766. 4096, 49, 4096,
  9767. };
  9768. const size_t num_it = 100;
  9769. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9770. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9771. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9772. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9773. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9774. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9775. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9776. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9777. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9778. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9779. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9780. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9781. abort();
  9782. for (size_t i = 0; i < vals.size(); i += 3) {
  9783. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9784. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9785. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9786. std::cerr << '\n';
  9787. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9788. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9789. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9790. std::cerr << '\n';
  9791. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9792. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9793. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9794. std::cerr << '\n' << std::endl;
  9795. if (vals[i + 2] % 32 == 0) {
  9796. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9797. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9798. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9799. std::cerr << '\n';
  9800. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9801. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9802. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9803. std::cerr << '\n';
  9804. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9805. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9806. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9807. std::cerr << '\n' << std::endl;
  9808. }
  9809. if (vals[i + 2] % 256 == 0) {
  9810. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9811. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9812. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9813. std::cerr << '\n';
  9814. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9815. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  9816. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  9817. std::cerr << '\n';
  9818. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  9819. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  9820. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  9821. std::cerr << '\n' << std::endl;
  9822. }
  9823. }
  9824. GGML_ABORT("fatal error");
  9825. #endif
  9826. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  9827. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  9828. // Resize buffer
  9829. if (ctx->prealloc_x != nullptr) {
  9830. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9831. }
  9832. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  9833. }
  9834. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  9835. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  9836. // Resize buffer
  9837. if (ctx->prealloc_y != nullptr) {
  9838. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9839. }
  9840. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  9841. }
  9842. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  9843. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  9844. // Resize buffer
  9845. if (ctx->prealloc_split_k != nullptr) {
  9846. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9847. }
  9848. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  9849. }
  9850. 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)) {
  9851. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  9852. // Resize buffer
  9853. if (ctx->prealloc_add_rms_partials != nullptr) {
  9854. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  9855. }
  9856. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  9857. }
  9858. }
  9859. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool use_fence, bool almost_ready);
  9860. // Returns true if node has enqueued work into the queue, false otherwise
  9861. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  9862. 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 dryrun, bool last_node, bool almost_ready, bool submit){
  9863. ggml_tensor * node = cgraph->nodes[node_idx];
  9864. if (ggml_is_empty(node) || !node->buffer) {
  9865. return false;
  9866. }
  9867. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  9868. ctx->semaphore_idx = 0;
  9869. ggml_tensor * src0 = node->src[0];
  9870. ggml_tensor * src1 = node->src[1];
  9871. ggml_tensor * src2 = node->src[2];
  9872. ggml_tensor * src3 = node->src[3];
  9873. switch (node->op) {
  9874. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  9875. case GGML_OP_RESHAPE:
  9876. case GGML_OP_VIEW:
  9877. case GGML_OP_PERMUTE:
  9878. case GGML_OP_TRANSPOSE:
  9879. case GGML_OP_NONE:
  9880. return false;
  9881. case GGML_OP_UNARY:
  9882. switch (ggml_get_unary_op(node)) {
  9883. case GGML_UNARY_OP_EXP:
  9884. case GGML_UNARY_OP_SILU:
  9885. case GGML_UNARY_OP_GELU:
  9886. case GGML_UNARY_OP_GELU_ERF:
  9887. case GGML_UNARY_OP_GELU_QUICK:
  9888. case GGML_UNARY_OP_RELU:
  9889. case GGML_UNARY_OP_TANH:
  9890. case GGML_UNARY_OP_SIGMOID:
  9891. case GGML_UNARY_OP_HARDSIGMOID:
  9892. case GGML_UNARY_OP_HARDSWISH:
  9893. break;
  9894. default:
  9895. return false;
  9896. }
  9897. break;
  9898. case GGML_OP_GLU:
  9899. switch (ggml_get_glu_op(node)) {
  9900. case GGML_GLU_OP_GEGLU:
  9901. case GGML_GLU_OP_REGLU:
  9902. case GGML_GLU_OP_SWIGLU:
  9903. case GGML_GLU_OP_SWIGLU_OAI:
  9904. case GGML_GLU_OP_GEGLU_ERF:
  9905. case GGML_GLU_OP_GEGLU_QUICK:
  9906. break;
  9907. default:
  9908. return false;
  9909. }
  9910. break;
  9911. case GGML_OP_ADD:
  9912. {
  9913. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  9914. if (next_node_idx < cgraph->n_nodes &&
  9915. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  9916. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  9917. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  9918. ctx->device->add_rms_fusion) {
  9919. if (dryrun) {
  9920. ctx->prealloc_size_add_rms_partials += ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  9921. }
  9922. ctx->do_add_rms_partials = true;
  9923. }
  9924. } break;
  9925. case GGML_OP_REPEAT:
  9926. case GGML_OP_REPEAT_BACK:
  9927. case GGML_OP_GET_ROWS:
  9928. case GGML_OP_ADD_ID:
  9929. case GGML_OP_ACC:
  9930. case GGML_OP_SUB:
  9931. case GGML_OP_MUL:
  9932. case GGML_OP_DIV:
  9933. case GGML_OP_CONCAT:
  9934. case GGML_OP_UPSCALE:
  9935. case GGML_OP_SCALE:
  9936. case GGML_OP_SQR:
  9937. case GGML_OP_SQRT:
  9938. case GGML_OP_SIN:
  9939. case GGML_OP_COS:
  9940. case GGML_OP_CLAMP:
  9941. case GGML_OP_PAD:
  9942. case GGML_OP_ROLL:
  9943. case GGML_OP_CPY:
  9944. case GGML_OP_SET_ROWS:
  9945. case GGML_OP_CONT:
  9946. case GGML_OP_DUP:
  9947. case GGML_OP_SILU_BACK:
  9948. case GGML_OP_NORM:
  9949. case GGML_OP_GROUP_NORM:
  9950. case GGML_OP_RMS_NORM:
  9951. case GGML_OP_RMS_NORM_BACK:
  9952. case GGML_OP_L2_NORM:
  9953. case GGML_OP_DIAG_MASK_INF:
  9954. case GGML_OP_SOFT_MAX:
  9955. case GGML_OP_SOFT_MAX_BACK:
  9956. case GGML_OP_ROPE:
  9957. case GGML_OP_ROPE_BACK:
  9958. case GGML_OP_MUL_MAT:
  9959. case GGML_OP_MUL_MAT_ID:
  9960. case GGML_OP_ARGSORT:
  9961. case GGML_OP_SUM:
  9962. case GGML_OP_SUM_ROWS:
  9963. case GGML_OP_MEAN:
  9964. case GGML_OP_ARGMAX:
  9965. case GGML_OP_COUNT_EQUAL:
  9966. case GGML_OP_IM2COL:
  9967. case GGML_OP_IM2COL_3D:
  9968. case GGML_OP_TIMESTEP_EMBEDDING:
  9969. case GGML_OP_CONV_TRANSPOSE_1D:
  9970. case GGML_OP_POOL_2D:
  9971. case GGML_OP_CONV_2D:
  9972. case GGML_OP_CONV_TRANSPOSE_2D:
  9973. case GGML_OP_CONV_2D_DW:
  9974. case GGML_OP_RWKV_WKV6:
  9975. case GGML_OP_RWKV_WKV7:
  9976. case GGML_OP_SSM_SCAN:
  9977. case GGML_OP_SSM_CONV:
  9978. case GGML_OP_LEAKY_RELU:
  9979. case GGML_OP_FLASH_ATTN_EXT:
  9980. case GGML_OP_OPT_STEP_ADAMW:
  9981. case GGML_OP_OPT_STEP_SGD:
  9982. break;
  9983. default:
  9984. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  9985. GGML_ABORT("fatal error");
  9986. }
  9987. vk_context compute_ctx;
  9988. if (!dryrun) {
  9989. if (ctx->compute_ctx.expired()) {
  9990. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9991. ctx->compute_ctx = compute_ctx;
  9992. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9993. } else {
  9994. compute_ctx = ctx->compute_ctx.lock();
  9995. }
  9996. } else {
  9997. switch (node->op) {
  9998. case GGML_OP_REPEAT:
  9999. case GGML_OP_REPEAT_BACK:
  10000. case GGML_OP_ACC:
  10001. case GGML_OP_GET_ROWS:
  10002. case GGML_OP_ADD:
  10003. case GGML_OP_SUB:
  10004. case GGML_OP_MUL:
  10005. case GGML_OP_DIV:
  10006. case GGML_OP_CONCAT:
  10007. case GGML_OP_UPSCALE:
  10008. case GGML_OP_SCALE:
  10009. case GGML_OP_SQR:
  10010. case GGML_OP_SQRT:
  10011. case GGML_OP_SIN:
  10012. case GGML_OP_COS:
  10013. case GGML_OP_CLAMP:
  10014. case GGML_OP_PAD:
  10015. case GGML_OP_CPY:
  10016. case GGML_OP_SET_ROWS:
  10017. case GGML_OP_CONT:
  10018. case GGML_OP_DUP:
  10019. case GGML_OP_SILU_BACK:
  10020. case GGML_OP_NORM:
  10021. case GGML_OP_GROUP_NORM:
  10022. case GGML_OP_RMS_NORM:
  10023. case GGML_OP_RMS_NORM_BACK:
  10024. case GGML_OP_L2_NORM:
  10025. case GGML_OP_UNARY:
  10026. case GGML_OP_GLU:
  10027. case GGML_OP_DIAG_MASK_INF:
  10028. case GGML_OP_SOFT_MAX:
  10029. case GGML_OP_SOFT_MAX_BACK:
  10030. case GGML_OP_ROPE_BACK:
  10031. case GGML_OP_ARGSORT:
  10032. case GGML_OP_SUM:
  10033. case GGML_OP_SUM_ROWS:
  10034. case GGML_OP_MEAN:
  10035. case GGML_OP_ARGMAX:
  10036. case GGML_OP_COUNT_EQUAL:
  10037. case GGML_OP_IM2COL:
  10038. case GGML_OP_IM2COL_3D:
  10039. case GGML_OP_TIMESTEP_EMBEDDING:
  10040. case GGML_OP_CONV_TRANSPOSE_1D:
  10041. case GGML_OP_POOL_2D:
  10042. case GGML_OP_CONV_2D:
  10043. case GGML_OP_CONV_TRANSPOSE_2D:
  10044. case GGML_OP_CONV_2D_DW:
  10045. case GGML_OP_LEAKY_RELU:
  10046. case GGML_OP_OPT_STEP_SGD:
  10047. {
  10048. // These operations all go through ggml_vk_op_f32, so short-circuit and
  10049. // do the only thing needed for the dryrun.
  10050. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  10051. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  10052. if (node->op == GGML_OP_RMS_NORM) {
  10053. ctx->do_add_rms_partials = false;
  10054. }
  10055. return false;
  10056. }
  10057. default:
  10058. break;
  10059. }
  10060. }
  10061. if (!dryrun) {
  10062. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  10063. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  10064. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  10065. // outside of this logic. When a node uses one of the prealloc buffers for something like
  10066. // dequantization or split_k, additional synchronization is needed between those passes.
  10067. bool need_sync = false;
  10068. // Check whether "node" requires synchronization. The node requires synchronization if it
  10069. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  10070. // Destination nodes are checked against both the written/read lists. Source nodes are only
  10071. // checked against the written list. Two nodes overlap in memory if they come from the same
  10072. // buffer and the tensor or view ranges overlap.
  10073. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  10074. if (unsynced_nodes.size() == 0) {
  10075. return false;
  10076. }
  10077. auto n_base = vk_tensor_offset(node) + node->view_offs;
  10078. auto n_size = ggml_nbytes(node);
  10079. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  10080. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10081. for (auto &other : unsynced_nodes) {
  10082. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  10083. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  10084. if (a_buf == o_buf) {
  10085. auto o_base = vk_tensor_offset(other) + other->view_offs;
  10086. auto o_size = ggml_nbytes(other);
  10087. if ((o_base <= n_base && n_base < o_base + o_size) ||
  10088. (n_base <= o_base && o_base < n_base + n_size)) {
  10089. return true;
  10090. }
  10091. }
  10092. }
  10093. return false;
  10094. };
  10095. // For all fused ops, check if the destination node or any of the source
  10096. // nodes require synchronization.
  10097. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  10098. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10099. // If the node actually writes to memory, then check if it needs to sync
  10100. if (ctx->fused_ops_write_mask & (1 << i)) {
  10101. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  10102. need_sync = true;
  10103. break;
  10104. }
  10105. }
  10106. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10107. if (!cur_node->src[j]) {
  10108. continue;
  10109. }
  10110. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  10111. need_sync = true;
  10112. break;
  10113. }
  10114. }
  10115. }
  10116. #define ENABLE_SYNC_LOGGING 0
  10117. if (need_sync) {
  10118. #if ENABLE_SYNC_LOGGING
  10119. std::cerr << "sync" << std::endl;
  10120. #endif
  10121. ctx->unsynced_nodes_written.clear();
  10122. ctx->unsynced_nodes_read.clear();
  10123. ggml_vk_sync_buffers(ctx, compute_ctx);
  10124. }
  10125. // Add all fused nodes to the unsynchronized lists.
  10126. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10127. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10128. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  10129. if (ctx->fused_ops_write_mask & (1 << i)) {
  10130. ctx->unsynced_nodes_written.push_back(cur_node);
  10131. }
  10132. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10133. if (!cur_node->src[j]) {
  10134. continue;
  10135. }
  10136. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  10137. }
  10138. }
  10139. }
  10140. #if ENABLE_SYNC_LOGGING
  10141. if (!dryrun) {
  10142. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10143. auto *n = cgraph->nodes[node_idx + i];
  10144. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  10145. if (n->op == GGML_OP_GLU) {
  10146. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  10147. }
  10148. std::cerr << std::endl;
  10149. }
  10150. }
  10151. #endif
  10152. switch (node->op) {
  10153. case GGML_OP_REPEAT:
  10154. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  10155. break;
  10156. case GGML_OP_REPEAT_BACK:
  10157. ggml_vk_repeat_back(ctx, compute_ctx, src0, node, dryrun);
  10158. break;
  10159. case GGML_OP_ACC:
  10160. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  10161. break;
  10162. case GGML_OP_GET_ROWS:
  10163. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  10164. break;
  10165. case GGML_OP_ADD:
  10166. if (ctx->num_additional_fused_ops) {
  10167. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx, dryrun);
  10168. } else {
  10169. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  10170. }
  10171. break;
  10172. case GGML_OP_SUB:
  10173. ggml_vk_sub(ctx, compute_ctx, src0, src1, node, dryrun);
  10174. break;
  10175. case GGML_OP_MUL:
  10176. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  10177. break;
  10178. case GGML_OP_DIV:
  10179. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  10180. break;
  10181. case GGML_OP_ADD_ID:
  10182. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  10183. break;
  10184. case GGML_OP_CONCAT:
  10185. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  10186. break;
  10187. case GGML_OP_UPSCALE:
  10188. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  10189. break;
  10190. case GGML_OP_SCALE:
  10191. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  10192. break;
  10193. case GGML_OP_SQR:
  10194. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  10195. break;
  10196. case GGML_OP_SQRT:
  10197. ggml_vk_sqrt(ctx, compute_ctx, src0, node, dryrun);
  10198. break;
  10199. case GGML_OP_SIN:
  10200. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  10201. break;
  10202. case GGML_OP_COS:
  10203. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  10204. break;
  10205. case GGML_OP_CLAMP:
  10206. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  10207. break;
  10208. case GGML_OP_PAD:
  10209. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  10210. break;
  10211. case GGML_OP_ROLL:
  10212. ggml_vk_roll(ctx, compute_ctx, src0, node, dryrun);
  10213. break;
  10214. case GGML_OP_CPY:
  10215. case GGML_OP_CONT:
  10216. case GGML_OP_DUP:
  10217. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  10218. break;
  10219. case GGML_OP_SET_ROWS:
  10220. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  10221. break;
  10222. case GGML_OP_SILU_BACK:
  10223. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node, dryrun);
  10224. break;
  10225. case GGML_OP_NORM:
  10226. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  10227. break;
  10228. case GGML_OP_GROUP_NORM:
  10229. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  10230. break;
  10231. case GGML_OP_RMS_NORM:
  10232. if (ctx->num_additional_fused_ops > 0) {
  10233. // fused rms_norm + mul
  10234. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10235. ggml_tensor *other_src = mul->src[0] == node ? mul->src[1] : mul->src[0];
  10236. ggml_vk_rms_norm(ctx, compute_ctx, src0, other_src, mul, (float *)node->op_params, dryrun);
  10237. } else {
  10238. ggml_vk_rms_norm(ctx, compute_ctx, src0, src0, node, (float *)node->op_params, dryrun);
  10239. }
  10240. break;
  10241. case GGML_OP_RMS_NORM_BACK:
  10242. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node, dryrun);
  10243. break;
  10244. case GGML_OP_L2_NORM:
  10245. ggml_vk_l2_norm(ctx, compute_ctx, src0, node, dryrun);
  10246. break;
  10247. case GGML_OP_UNARY:
  10248. switch (ggml_get_unary_op(node)) {
  10249. case GGML_UNARY_OP_EXP:
  10250. case GGML_UNARY_OP_SILU:
  10251. case GGML_UNARY_OP_GELU:
  10252. case GGML_UNARY_OP_GELU_ERF:
  10253. case GGML_UNARY_OP_GELU_QUICK:
  10254. case GGML_UNARY_OP_RELU:
  10255. case GGML_UNARY_OP_TANH:
  10256. case GGML_UNARY_OP_SIGMOID:
  10257. case GGML_UNARY_OP_HARDSIGMOID:
  10258. case GGML_UNARY_OP_HARDSWISH:
  10259. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  10260. break;
  10261. default:
  10262. return false;
  10263. }
  10264. break;
  10265. case GGML_OP_GLU:
  10266. switch (ggml_get_glu_op(node)) {
  10267. case GGML_GLU_OP_GEGLU:
  10268. case GGML_GLU_OP_REGLU:
  10269. case GGML_GLU_OP_SWIGLU:
  10270. case GGML_GLU_OP_SWIGLU_OAI:
  10271. case GGML_GLU_OP_GEGLU_ERF:
  10272. case GGML_GLU_OP_GEGLU_QUICK:
  10273. ggml_vk_glu(ctx, compute_ctx, src0, src1, node, dryrun);
  10274. break;
  10275. default:
  10276. return false;
  10277. }
  10278. break;
  10279. case GGML_OP_DIAG_MASK_INF:
  10280. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  10281. break;
  10282. case GGML_OP_SOFT_MAX:
  10283. if (ctx->num_additional_fused_ops) {
  10284. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx, dryrun);
  10285. } else {
  10286. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  10287. }
  10288. break;
  10289. case GGML_OP_SOFT_MAX_BACK:
  10290. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node, dryrun);
  10291. break;
  10292. case GGML_OP_ROPE:
  10293. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false, dryrun);
  10294. break;
  10295. case GGML_OP_ROPE_BACK:
  10296. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true, dryrun);
  10297. break;
  10298. case GGML_OP_ARGSORT:
  10299. if (ctx->num_additional_fused_ops) {
  10300. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx, dryrun);
  10301. } else {
  10302. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  10303. }
  10304. break;
  10305. case GGML_OP_SUM:
  10306. ggml_vk_sum(ctx, compute_ctx, src0, node, dryrun);
  10307. break;
  10308. case GGML_OP_SUM_ROWS:
  10309. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  10310. break;
  10311. case GGML_OP_MEAN:
  10312. ggml_vk_mean(ctx, compute_ctx, src0, node, dryrun);
  10313. break;
  10314. case GGML_OP_ARGMAX:
  10315. ggml_vk_argmax(ctx, compute_ctx, src0, node, dryrun);
  10316. break;
  10317. case GGML_OP_COUNT_EQUAL:
  10318. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node, dryrun);
  10319. break;
  10320. case GGML_OP_IM2COL:
  10321. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  10322. break;
  10323. case GGML_OP_IM2COL_3D:
  10324. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node, dryrun);
  10325. break;
  10326. case GGML_OP_TIMESTEP_EMBEDDING:
  10327. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  10328. break;
  10329. case GGML_OP_CONV_TRANSPOSE_1D:
  10330. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node, dryrun);
  10331. break;
  10332. case GGML_OP_POOL_2D:
  10333. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  10334. break;
  10335. case GGML_OP_CONV_2D:
  10336. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  10337. break;
  10338. case GGML_OP_CONV_TRANSPOSE_2D:
  10339. ggml_vk_conv_transpose_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  10340. break;
  10341. case GGML_OP_CONV_2D_DW:
  10342. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node, dryrun);
  10343. break;
  10344. case GGML_OP_LEAKY_RELU:
  10345. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  10346. break;
  10347. case GGML_OP_MUL_MAT:
  10348. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx, dryrun);
  10349. break;
  10350. case GGML_OP_MUL_MAT_ID:
  10351. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx, dryrun);
  10352. break;
  10353. case GGML_OP_FLASH_ATTN_EXT:
  10354. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node, dryrun);
  10355. break;
  10356. case GGML_OP_RWKV_WKV6:
  10357. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node, dryrun);
  10358. break;
  10359. case GGML_OP_RWKV_WKV7:
  10360. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node, dryrun);
  10361. break;
  10362. case GGML_OP_SSM_SCAN:
  10363. ggml_vk_ssm_scan(ctx, compute_ctx, node, dryrun);
  10364. break;
  10365. case GGML_OP_SSM_CONV:
  10366. ggml_vk_ssm_conv(ctx, compute_ctx, node, dryrun);
  10367. break;
  10368. case GGML_OP_OPT_STEP_ADAMW:
  10369. ggml_vk_opt_step_adamw(ctx, compute_ctx, node, dryrun);
  10370. break;
  10371. case GGML_OP_OPT_STEP_SGD:
  10372. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  10373. break;
  10374. default:
  10375. return false;
  10376. }
  10377. if (dryrun) {
  10378. return false;
  10379. }
  10380. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10381. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10382. // Force context reset on each node so that each tensor ends up in its own context
  10383. // and can be run and compared to its CPU equivalent separately
  10384. last_node = true;
  10385. #endif
  10386. if (submit || last_node) {
  10387. ggml_vk_ctx_end(compute_ctx);
  10388. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10389. if (last_node) {
  10390. compute_ctx->exit_tensor_idx = node_idx_begin;
  10391. }
  10392. else {
  10393. compute_ctx->exit_tensor_idx = -1;
  10394. }
  10395. ctx->compute_ctx.reset();
  10396. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, false, almost_ready);
  10397. if (!ok) {
  10398. if (node->op == GGML_OP_UNARY) {
  10399. std::cerr << __func__ << ": error: op not supported UNARY " << node->name << " (" << ggml_unary_op_name(static_cast<ggml_unary_op>(node->op_params[0])) << ")" << std::endl;
  10400. } else if (node->op == GGML_OP_GLU) {
  10401. std::cerr << __func__ << ": error: op not supported GLU " << node->name << " (" << ggml_glu_op_name(static_cast<ggml_glu_op>(node->op_params[0])) << ")" << std::endl;
  10402. } else {
  10403. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  10404. }
  10405. }
  10406. }
  10407. return true;
  10408. }
  10409. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool use_fence = true, bool almost_ready = false) {
  10410. GGML_UNUSED(cgraph);
  10411. ggml_backend_buffer * buf = nullptr;
  10412. switch (tensor->op) {
  10413. case GGML_OP_ADD:
  10414. case GGML_OP_ACC:
  10415. case GGML_OP_GET_ROWS:
  10416. case GGML_OP_SUB:
  10417. case GGML_OP_MUL:
  10418. case GGML_OP_DIV:
  10419. case GGML_OP_ADD_ID:
  10420. case GGML_OP_CONCAT:
  10421. case GGML_OP_UPSCALE:
  10422. case GGML_OP_SCALE:
  10423. case GGML_OP_SQR:
  10424. case GGML_OP_SQRT:
  10425. case GGML_OP_SIN:
  10426. case GGML_OP_COS:
  10427. case GGML_OP_CLAMP:
  10428. case GGML_OP_PAD:
  10429. case GGML_OP_ROLL:
  10430. case GGML_OP_CPY:
  10431. case GGML_OP_SET_ROWS:
  10432. case GGML_OP_CONT:
  10433. case GGML_OP_DUP:
  10434. case GGML_OP_SILU_BACK:
  10435. case GGML_OP_NORM:
  10436. case GGML_OP_GROUP_NORM:
  10437. case GGML_OP_RMS_NORM:
  10438. case GGML_OP_RMS_NORM_BACK:
  10439. case GGML_OP_L2_NORM:
  10440. case GGML_OP_DIAG_MASK_INF:
  10441. case GGML_OP_SOFT_MAX:
  10442. case GGML_OP_SOFT_MAX_BACK:
  10443. case GGML_OP_ROPE:
  10444. case GGML_OP_ROPE_BACK:
  10445. case GGML_OP_RESHAPE:
  10446. case GGML_OP_VIEW:
  10447. case GGML_OP_PERMUTE:
  10448. case GGML_OP_TRANSPOSE:
  10449. case GGML_OP_NONE:
  10450. case GGML_OP_ARGSORT:
  10451. case GGML_OP_SUM:
  10452. case GGML_OP_SUM_ROWS:
  10453. case GGML_OP_MEAN:
  10454. case GGML_OP_ARGMAX:
  10455. case GGML_OP_COUNT_EQUAL:
  10456. case GGML_OP_IM2COL:
  10457. case GGML_OP_IM2COL_3D:
  10458. case GGML_OP_TIMESTEP_EMBEDDING:
  10459. case GGML_OP_CONV_TRANSPOSE_1D:
  10460. case GGML_OP_POOL_2D:
  10461. case GGML_OP_CONV_2D:
  10462. case GGML_OP_CONV_TRANSPOSE_2D:
  10463. case GGML_OP_CONV_2D_DW:
  10464. case GGML_OP_RWKV_WKV6:
  10465. case GGML_OP_RWKV_WKV7:
  10466. case GGML_OP_SSM_SCAN:
  10467. case GGML_OP_SSM_CONV:
  10468. case GGML_OP_LEAKY_RELU:
  10469. case GGML_OP_REPEAT:
  10470. case GGML_OP_REPEAT_BACK:
  10471. case GGML_OP_OPT_STEP_ADAMW:
  10472. case GGML_OP_OPT_STEP_SGD:
  10473. buf = tensor->buffer;
  10474. break;
  10475. case GGML_OP_UNARY:
  10476. switch (ggml_get_unary_op(tensor)) {
  10477. case GGML_UNARY_OP_EXP:
  10478. case GGML_UNARY_OP_SILU:
  10479. case GGML_UNARY_OP_GELU:
  10480. case GGML_UNARY_OP_GELU_ERF:
  10481. case GGML_UNARY_OP_GELU_QUICK:
  10482. case GGML_UNARY_OP_RELU:
  10483. case GGML_UNARY_OP_TANH:
  10484. case GGML_UNARY_OP_SIGMOID:
  10485. case GGML_UNARY_OP_HARDSIGMOID:
  10486. case GGML_UNARY_OP_HARDSWISH:
  10487. buf = tensor->buffer;
  10488. break;
  10489. default:
  10490. return false;
  10491. }
  10492. break;
  10493. case GGML_OP_GLU:
  10494. switch (ggml_get_glu_op(tensor)) {
  10495. case GGML_GLU_OP_GEGLU:
  10496. case GGML_GLU_OP_REGLU:
  10497. case GGML_GLU_OP_SWIGLU:
  10498. case GGML_GLU_OP_SWIGLU_OAI:
  10499. case GGML_GLU_OP_GEGLU_ERF:
  10500. case GGML_GLU_OP_GEGLU_QUICK:
  10501. buf = tensor->buffer;
  10502. break;
  10503. default:
  10504. return false;
  10505. }
  10506. break;
  10507. case GGML_OP_MUL_MAT:
  10508. case GGML_OP_MUL_MAT_ID:
  10509. case GGML_OP_FLASH_ATTN_EXT:
  10510. buf = tensor->buffer;
  10511. break;
  10512. default:
  10513. return false;
  10514. }
  10515. if (buf == nullptr) {
  10516. return false;
  10517. }
  10518. 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 << ")");
  10519. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10520. // always wait for the GPU work to be done for the last submit
  10521. if (tensor_idx == subctx->exit_tensor_idx) {
  10522. use_fence = true;
  10523. }
  10524. // Only run if ctx hasn't been submitted yet
  10525. if (!subctx->seqs.empty()) {
  10526. #ifdef GGML_VULKAN_CHECK_RESULTS
  10527. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10528. use_fence = true;
  10529. #endif
  10530. // Do staging buffer copies
  10531. for (auto& cpy : subctx->in_memcpys) {
  10532. memcpy(cpy.dst, cpy.src, cpy.n);
  10533. }
  10534. for (auto& mset : subctx->memsets) {
  10535. memset(mset.dst, mset.val, mset.n);
  10536. }
  10537. if (almost_ready && !ctx->almost_ready_fence_pending && !use_fence) {
  10538. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10539. ctx->almost_ready_fence_pending = true;
  10540. } else {
  10541. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  10542. }
  10543. if (use_fence) {
  10544. ggml_vk_wait_for_fence(ctx);
  10545. }
  10546. #ifdef GGML_VULKAN_CHECK_RESULTS
  10547. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10548. #endif
  10549. }
  10550. if (tensor_idx == subctx->exit_tensor_idx) {
  10551. // Do staging buffer copies
  10552. for (auto& cpy : subctx->out_memcpys) {
  10553. memcpy(cpy.dst, cpy.src, cpy.n);
  10554. }
  10555. subctx->in_memcpys.clear();
  10556. subctx->out_memcpys.clear();
  10557. subctx->memsets.clear();
  10558. }
  10559. return true;
  10560. }
  10561. // Clean up after graph processing is done
  10562. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10563. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10564. ctx->prealloc_y_last_pipeline_used = {};
  10565. ctx->unsynced_nodes_written.clear();
  10566. ctx->unsynced_nodes_read.clear();
  10567. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10568. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10569. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10570. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10571. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10572. }
  10573. ctx->gc.semaphores.clear();
  10574. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10575. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10576. }
  10577. ctx->gc.tl_semaphores.clear();
  10578. ctx->semaphore_idx = 0;
  10579. ctx->event_idx = 0;
  10580. for (auto& event : ctx->gc.events) {
  10581. ctx->device->device.resetEvent(event);
  10582. }
  10583. ctx->tensor_ctxs.clear();
  10584. ctx->gc.contexts.clear();
  10585. ctx->pipeline_descriptor_set_requirements = 0;
  10586. ctx->descriptor_set_idx = 0;
  10587. }
  10588. // Clean up on backend free
  10589. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10590. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10591. ggml_vk_graph_cleanup(ctx);
  10592. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10593. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10594. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10595. ctx->prealloc_y_last_pipeline_used = nullptr;
  10596. ctx->prealloc_size_x = 0;
  10597. ctx->prealloc_size_y = 0;
  10598. ctx->prealloc_size_split_k = 0;
  10599. for (auto& event : ctx->gc.events) {
  10600. ctx->device->device.destroyEvent(event);
  10601. }
  10602. ctx->gc.events.clear();
  10603. ctx->device->device.destroyFence(ctx->fence);
  10604. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10605. for (auto& pool : ctx->descriptor_pools) {
  10606. ctx->device->device.destroyDescriptorPool(pool);
  10607. }
  10608. ctx->descriptor_pools.clear();
  10609. ctx->descriptor_sets.clear();
  10610. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10611. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10612. }
  10613. static int ggml_vk_get_device_count() {
  10614. ggml_vk_instance_init();
  10615. return vk_instance.device_indices.size();
  10616. }
  10617. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10618. ggml_vk_instance_init();
  10619. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10620. vk::PhysicalDeviceProperties props;
  10621. devices[device].getProperties(&props);
  10622. snprintf(description, description_size, "%s", props.deviceName.data());
  10623. }
  10624. // backend interface
  10625. #define UNUSED GGML_UNUSED
  10626. // device backend
  10627. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10628. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10629. }
  10630. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10631. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10632. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10633. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10634. delete ctx;
  10635. }
  10636. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10637. return vk_ptr_base;
  10638. UNUSED(buffer);
  10639. }
  10640. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10641. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10642. if (tensor->view_src != nullptr) {
  10643. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10644. }
  10645. return GGML_STATUS_SUCCESS;
  10646. }
  10647. 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) {
  10648. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10649. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10650. vk_buffer buf = buf_ctx->dev_buffer;
  10651. uint32_t val32 = (uint32_t)value * 0x01010101;
  10652. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10653. }
  10654. 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) {
  10655. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10656. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10657. vk_buffer buf = buf_ctx->dev_buffer;
  10658. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10659. }
  10660. 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) {
  10661. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10662. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10663. vk_buffer buf = buf_ctx->dev_buffer;
  10664. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10665. }
  10666. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10667. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10668. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10669. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10670. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10671. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10672. 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));
  10673. return true;
  10674. }
  10675. return false;
  10676. UNUSED(buffer);
  10677. }
  10678. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10679. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10680. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10681. }
  10682. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10683. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10684. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10685. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10686. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10687. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10688. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10689. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10690. /* .clear = */ ggml_backend_vk_buffer_clear,
  10691. /* .reset = */ NULL,
  10692. };
  10693. // vk buffer type
  10694. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10695. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10696. return ctx->name.c_str();
  10697. }
  10698. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10699. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10700. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10701. vk_buffer dev_buffer = nullptr;
  10702. try {
  10703. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10704. } catch (const vk::SystemError& e) {
  10705. return nullptr;
  10706. }
  10707. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10708. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10709. }
  10710. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10711. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10712. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10713. }
  10714. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10715. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10716. return ctx->device->suballocation_block_size;
  10717. }
  10718. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10719. return ggml_nbytes(tensor);
  10720. UNUSED(buft);
  10721. }
  10722. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10723. ggml_vk_instance_init();
  10724. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10725. vk_device dev = ggml_vk_get_device(dev_num);
  10726. return &dev->buffer_type;
  10727. }
  10728. // host buffer type
  10729. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10730. return GGML_VK_NAME "_Host";
  10731. UNUSED(buft);
  10732. }
  10733. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10734. return GGML_VK_NAME "_Host";
  10735. UNUSED(buffer);
  10736. }
  10737. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10738. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10739. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10740. }
  10741. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10742. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10743. size += 32; // Behave like the CPU buffer type
  10744. void * ptr = nullptr;
  10745. try {
  10746. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10747. } catch (vk::SystemError& e) {
  10748. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10749. // fallback to cpu buffer
  10750. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10751. }
  10752. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10753. buffer->buft = buft;
  10754. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10755. return buffer;
  10756. UNUSED(buft);
  10757. }
  10758. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10759. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10760. UNUSED(buft);
  10761. }
  10762. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10763. return vk_instance.devices[0]->suballocation_block_size;
  10764. UNUSED(buft);
  10765. }
  10766. // Should be changed to return device-specific host buffer type
  10767. // but that probably requires changes in llama.cpp
  10768. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10769. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10770. /* .iface = */ {
  10771. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10772. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10773. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10774. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10775. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10776. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10777. },
  10778. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10779. /* .context = */ nullptr,
  10780. };
  10781. // Make sure device 0 is initialized
  10782. ggml_vk_instance_init();
  10783. ggml_vk_get_device(0);
  10784. return &ggml_backend_vk_buffer_type_host;
  10785. }
  10786. // backend
  10787. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10788. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10789. return ctx->name.c_str();
  10790. }
  10791. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10792. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10793. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10794. ggml_vk_cleanup(ctx);
  10795. delete ctx;
  10796. delete backend;
  10797. }
  10798. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10799. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10800. return &ctx->device->buffer_type;
  10801. }
  10802. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10803. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10804. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10805. 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");
  10806. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10807. vk_context transfer_ctx;
  10808. if (ctx->transfer_ctx.expired()) {
  10809. // Initialize new transfer context
  10810. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10811. ctx->transfer_ctx = transfer_ctx;
  10812. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10813. } else {
  10814. transfer_ctx = ctx->transfer_ctx.lock();
  10815. }
  10816. vk_buffer buf = buf_ctx->dev_buffer;
  10817. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10818. }
  10819. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10820. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10821. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10822. 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");
  10823. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10824. vk_context transfer_ctx;
  10825. if (ctx->transfer_ctx.expired()) {
  10826. // Initialize new transfer context
  10827. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10828. ctx->transfer_ctx = transfer_ctx;
  10829. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10830. } else {
  10831. transfer_ctx = ctx->transfer_ctx.lock();
  10832. }
  10833. vk_buffer buf = buf_ctx->dev_buffer;
  10834. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10835. }
  10836. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10837. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10838. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10839. 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)) {
  10840. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10841. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10842. vk_context transfer_ctx;
  10843. if (ctx->transfer_ctx.expired()) {
  10844. // Initialize new transfer context
  10845. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10846. ctx->transfer_ctx = transfer_ctx;
  10847. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10848. } else {
  10849. transfer_ctx = ctx->transfer_ctx.lock();
  10850. }
  10851. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10852. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10853. 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));
  10854. return true;
  10855. }
  10856. return false;
  10857. }
  10858. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10859. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10860. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10861. if(ctx->transfer_ctx.expired()) {
  10862. return;
  10863. }
  10864. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  10865. ggml_vk_ctx_end(transfer_ctx);
  10866. for (auto& cpy : transfer_ctx->in_memcpys) {
  10867. memcpy(cpy.dst, cpy.src, cpy.n);
  10868. }
  10869. ggml_vk_submit(transfer_ctx, ctx->fence);
  10870. ggml_vk_wait_for_fence(ctx);
  10871. for (auto& cpy : transfer_ctx->out_memcpys) {
  10872. memcpy(cpy.dst, cpy.src, cpy.n);
  10873. }
  10874. ctx->transfer_ctx.reset();
  10875. }
  10876. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10877. 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;
  10878. }
  10879. 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) {
  10880. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10881. return false;
  10882. }
  10883. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10884. // additional constraints specific to this fusion
  10885. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10886. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10887. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10888. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10889. // rms_norm only supports f32
  10890. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10891. mul->src[1]->type != GGML_TYPE_F32 ||
  10892. mul->type != GGML_TYPE_F32) {
  10893. return false;
  10894. }
  10895. // if rms_norm is the B operand, then we don't handle broadcast
  10896. if (rms_norm == mul->src[1] &&
  10897. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10898. return false;
  10899. }
  10900. // rms_norm shader assumes contiguous rows
  10901. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10902. return false;
  10903. }
  10904. }
  10905. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  10906. // additional constraints specific to this fusion
  10907. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10908. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10909. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  10910. // mat-vec only
  10911. if (ggml_nrows(mul) != 1) {
  10912. return false;
  10913. }
  10914. // shaders assume the types match
  10915. if (mul->type != bias->type) {
  10916. return false;
  10917. }
  10918. // shaders reuse the D shape for bias
  10919. if (!ggml_are_same_shape(mul, bias) ||
  10920. !ggml_are_same_stride(mul, bias)) {
  10921. return false;
  10922. }
  10923. // unaligned bias isn't handled
  10924. if (get_misalign_bytes(ctx, bias) != 0) {
  10925. return false;
  10926. }
  10927. }
  10928. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  10929. // additional constraints specific to this fusion
  10930. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10931. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10932. const ggml_tensor *bias = add->src[1];
  10933. if (mul != add->src[0]) {
  10934. return false;
  10935. }
  10936. // mat-vec only
  10937. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10938. return false;
  10939. }
  10940. // shaders assume the types match
  10941. if (mul->type != bias->type) {
  10942. return false;
  10943. }
  10944. // shaders assume the bias is contiguous
  10945. if (!ggml_is_contiguous(bias)) {
  10946. return false;
  10947. }
  10948. // the ID tensor must be the same for mul_mat_id and add_id
  10949. if (mul->src[2] != add->src[2]) {
  10950. return false;
  10951. }
  10952. // unaligned bias isn't handled
  10953. if (get_misalign_bytes(ctx, bias) != 0) {
  10954. return false;
  10955. }
  10956. }
  10957. return true;
  10958. }
  10959. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10960. int node_idx, topk_moe_mode mode) {
  10961. const ggml_tensor * softmax;
  10962. const ggml_tensor * weights;
  10963. switch (mode) {
  10964. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  10965. softmax = cgraph->nodes[node_idx + 0];
  10966. weights = cgraph->nodes[node_idx + 9];
  10967. break;
  10968. case TOPK_MOE_EARLY_SOFTMAX:
  10969. softmax = cgraph->nodes[node_idx + 0];
  10970. weights = cgraph->nodes[node_idx + 4];
  10971. break;
  10972. case TOPK_MOE_LATE_SOFTMAX:
  10973. softmax = cgraph->nodes[node_idx + 4];
  10974. weights = cgraph->nodes[node_idx + 5];
  10975. break;
  10976. default:
  10977. return false;
  10978. }
  10979. const float * op_params = (const float *)softmax->op_params;
  10980. float scale = op_params[0];
  10981. float max_bias = op_params[1];
  10982. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  10983. return false;
  10984. }
  10985. if (scale != 1.0f || max_bias != 0.0f) {
  10986. return false;
  10987. }
  10988. // don't fuse when masks or sinks are present
  10989. if (softmax->src[1] || softmax->src[2]) {
  10990. return false;
  10991. }
  10992. const int n_expert = softmax->ne[0];
  10993. // n_expert must be a power of 2
  10994. if (!is_pow2(n_expert) || n_expert > (1 << (num_topk_moe_pipelines-1))) {
  10995. return false;
  10996. }
  10997. if (!ctx->device->subgroup_arithmetic ||
  10998. !ctx->device->subgroup_shuffle ||
  10999. !ctx->device->subgroup_require_full_support ||
  11000. ctx->device->disable_fusion) {
  11001. return false;
  11002. }
  11003. return true;
  11004. }
  11005. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11006. int node_idx) {
  11007. GGML_UNUSED(ctx);
  11008. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  11009. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  11010. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  11011. // ne3 not tested
  11012. if (rope->src[0]->ne[3] != 1) {
  11013. return false;
  11014. }
  11015. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  11016. return false;
  11017. }
  11018. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  11019. return false;
  11020. }
  11021. // The view should flatten two dims of rope into one dim
  11022. if (!ggml_is_contiguous(view) ||
  11023. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  11024. return false;
  11025. }
  11026. // Only norm/neox shaders have the fusion code
  11027. const int mode = ((const int32_t *) rope->op_params)[2];
  11028. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
  11029. return false;
  11030. }
  11031. return true;
  11032. }
  11033. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  11034. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  11035. if (first_node->op != GGML_OP_ADD) {
  11036. return 0;
  11037. }
  11038. if (!ctx->device->multi_add) {
  11039. return 0;
  11040. }
  11041. int32_t num_adds = 1;
  11042. while (node_idx + num_adds < cgraph->n_nodes &&
  11043. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  11044. num_adds < MAX_FUSED_ADDS) {
  11045. num_adds++;
  11046. }
  11047. // The shader currently requires same shapes (but different strides are allowed),
  11048. // everything f32, and no misalignment
  11049. for (int32_t i = 0; i < num_adds; ++i) {
  11050. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  11051. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  11052. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  11053. next_node->type != GGML_TYPE_F32 ||
  11054. next_node->src[0]->type != GGML_TYPE_F32 ||
  11055. next_node->src[1]->type != GGML_TYPE_F32 ||
  11056. get_misalign_bytes(ctx, next_node) ||
  11057. get_misalign_bytes(ctx, next_node->src[0]) ||
  11058. get_misalign_bytes(ctx, next_node->src[1])) {
  11059. num_adds = i;
  11060. }
  11061. }
  11062. // Verify we can fuse these
  11063. ggml_op adds[MAX_FUSED_ADDS];
  11064. for (int32_t i = 0; i < num_adds; ++i) {
  11065. adds[i] = GGML_OP_ADD;
  11066. }
  11067. // decrease num_adds if they can't all be fused
  11068. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  11069. num_adds--;
  11070. }
  11071. // a single add is not "fused", so just return zero
  11072. if (num_adds == 1) {
  11073. return 0;
  11074. }
  11075. return num_adds;
  11076. }
  11077. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  11078. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  11079. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11080. if (vk_instance.debug_utils_support) {
  11081. vk::DebugUtilsLabelEXT dul = {};
  11082. dul.pLabelName = "ggml_backend_vk_graph_compute";
  11083. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  11084. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  11085. }
  11086. ctx->prealloc_size_add_rms_partials = 0;
  11087. ctx->prealloc_size_add_rms_partials_offset = 0;
  11088. ctx->do_add_rms_partials = false;
  11089. uint64_t total_mat_mul_bytes = 0;
  11090. for (int i = 0; i < cgraph->n_nodes; i++) {
  11091. if (!ctx->device->disable_fusion) {
  11092. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11093. if (num_adds) {
  11094. ctx->num_additional_fused_ops = num_adds - 1;
  11095. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11096. ctx->num_additional_fused_ops = 1;
  11097. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11098. ctx->num_additional_fused_ops = 1;
  11099. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11100. ctx->num_additional_fused_ops = 1;
  11101. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11102. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11103. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11104. ctx->num_additional_fused_ops = 2;
  11105. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11106. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11107. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11108. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11109. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11110. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11111. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11112. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11113. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11114. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11115. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11116. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11117. }
  11118. }
  11119. ggml_vk_build_graph(ctx, cgraph, i, nullptr, 0, true, false, false, false);
  11120. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11121. total_mat_mul_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  11122. } else if (cgraph->nodes[i]->op == GGML_OP_CONV_2D || cgraph->nodes[i]->op == GGML_OP_CONV_TRANSPOSE_2D) {
  11123. // Return CRSxNPQxsizeof(*) to account as many bytes as mul_mat has in im2col->mul_mat mode.
  11124. auto CRS_size =
  11125. cgraph->nodes[i]->src[0]->ne[0] * cgraph->nodes[i]->src[0]->ne[1] * cgraph->nodes[i]->src[1]->ne[2];
  11126. auto NPQ_size = cgraph->nodes[i]->ne[0] * cgraph->nodes[i]->ne[1] * cgraph->nodes[i]->ne[3];
  11127. total_mat_mul_bytes += NPQ_size * CRS_size * ggml_type_size(cgraph->nodes[i]->type);
  11128. }
  11129. i += ctx->num_additional_fused_ops;
  11130. ctx->num_additional_fused_ops = 0;
  11131. }
  11132. if (ctx->device->need_compiles) {
  11133. ggml_vk_load_shaders(ctx->device);
  11134. }
  11135. ggml_vk_preallocate_buffers(ctx);
  11136. ggml_pipeline_allocate_descriptor_sets(ctx);
  11137. int last_node = cgraph->n_nodes - 1;
  11138. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  11139. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  11140. last_node -= 1;
  11141. }
  11142. // Reserve tensor context space for all nodes
  11143. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  11144. bool first_node_in_batch = true; // true if next node will be first node in a batch
  11145. int submit_node_idx = 0; // index to first node in a batch
  11146. vk_context compute_ctx;
  11147. if (vk_perf_logger_enabled) {
  11148. // allocate/resize the query pool
  11149. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  11150. if (ctx->device->query_pool) {
  11151. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  11152. }
  11153. vk::QueryPoolCreateInfo query_create_info;
  11154. query_create_info.queryType = vk::QueryType::eTimestamp;
  11155. query_create_info.queryCount = cgraph->n_nodes + 100;
  11156. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  11157. ctx->device->num_queries = query_create_info.queryCount;
  11158. }
  11159. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  11160. GGML_ASSERT(ctx->compute_ctx.expired());
  11161. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11162. ctx->compute_ctx = compute_ctx;
  11163. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11164. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  11165. }
  11166. ctx->prealloc_y_last_pipeline_used = nullptr;
  11167. ctx->prealloc_y_last_tensor_used = nullptr;
  11168. if (ctx->prealloc_size_add_rms_partials) {
  11169. if (ctx->compute_ctx.expired()) {
  11170. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11171. ctx->compute_ctx = compute_ctx;
  11172. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11173. } else {
  11174. compute_ctx = ctx->compute_ctx.lock();
  11175. }
  11176. // initialize partial sums to zero.
  11177. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  11178. ggml_vk_sync_buffers(ctx, compute_ctx);
  11179. }
  11180. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  11181. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  11182. // (and scaled down based on model size, so smaller models submit earlier).
  11183. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  11184. int nodes_per_submit = 100;
  11185. int submitted_nodes = 0;
  11186. int submit_count = 0;
  11187. uint64_t mul_mat_bytes = 0;
  11188. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), total_mat_mul_bytes / 40u);
  11189. for (int i = 0; i < cgraph->n_nodes; i++) {
  11190. if (first_node_in_batch) {
  11191. submit_node_idx = i;
  11192. }
  11193. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11194. mul_mat_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  11195. }
  11196. if (!ctx->device->disable_fusion) {
  11197. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11198. if (num_adds) {
  11199. ctx->num_additional_fused_ops = num_adds - 1;
  11200. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11201. ctx->num_additional_fused_ops = 1;
  11202. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11203. ctx->num_additional_fused_ops = 1;
  11204. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11205. ctx->num_additional_fused_ops = 1;
  11206. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11207. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11208. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11209. ctx->num_additional_fused_ops = 2;
  11210. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11211. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11212. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11213. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11214. // view of argsort writes to memory
  11215. ctx->fused_ops_write_mask |= 1 << 3;
  11216. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11217. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11218. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11219. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11220. // view of argsort writes to memory
  11221. ctx->fused_ops_write_mask |= 1 << 3;
  11222. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11223. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11224. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11225. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11226. // view of argsort writes to memory
  11227. ctx->fused_ops_write_mask |= 1 << 1;
  11228. }
  11229. }
  11230. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  11231. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  11232. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  11233. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11234. (mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11235. (i + ctx->num_additional_fused_ops >= last_node) ||
  11236. (almost_ready && !ctx->almost_ready_fence_pending);
  11237. bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, false, i + ctx->num_additional_fused_ops >= last_node, almost_ready, submit);
  11238. if (vk_perf_logger_enabled) {
  11239. if (ctx->compute_ctx.expired()) {
  11240. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11241. ctx->compute_ctx = compute_ctx;
  11242. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11243. } else {
  11244. compute_ctx = ctx->compute_ctx.lock();
  11245. }
  11246. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  11247. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  11248. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  11249. }
  11250. }
  11251. if (enqueued) {
  11252. ++submitted_nodes;
  11253. #ifndef GGML_VULKAN_CHECK_RESULTS
  11254. if (first_node_in_batch) {
  11255. first_node_in_batch = false;
  11256. }
  11257. #endif
  11258. }
  11259. if (submit && enqueued) {
  11260. first_node_in_batch = true;
  11261. submitted_nodes = 0;
  11262. mul_mat_bytes = 0;
  11263. if (submit_count < 3) {
  11264. mul_mat_bytes_per_submit *= 2;
  11265. }
  11266. submit_count++;
  11267. }
  11268. i += ctx->num_additional_fused_ops;
  11269. ctx->num_additional_fused_ops = 0;
  11270. ctx->fused_ops_write_mask = 0;
  11271. }
  11272. if (vk_perf_logger_enabled) {
  11273. // End the command buffer and submit/wait
  11274. GGML_ASSERT(!ctx->compute_ctx.expired());
  11275. compute_ctx = ctx->compute_ctx.lock();
  11276. ggml_vk_ctx_end(compute_ctx);
  11277. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11278. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11279. ctx->device->device.resetFences({ ctx->device->fence });
  11280. // Get the results and pass them to the logger
  11281. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11282. VK_CHECK(ctx->device->device.getQueryPoolResults(ctx->device->query_pool, 0, cgraph->n_nodes + 1, (cgraph->n_nodes + 1)*sizeof(uint64_t), timestamps.data(), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait), "get timestamp results");
  11283. for (int i = 0; i < cgraph->n_nodes; i++) {
  11284. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  11285. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  11286. }
  11287. }
  11288. ctx->device->perf_logger->print_timings();
  11289. }
  11290. ggml_vk_graph_cleanup(ctx);
  11291. return GGML_STATUS_SUCCESS;
  11292. UNUSED(backend);
  11293. }
  11294. // Sort the graph for improved parallelism.
  11295. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11296. {
  11297. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11298. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11299. if (ctx->device->disable_graph_optimize) {
  11300. return;
  11301. }
  11302. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11303. 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;
  11304. };
  11305. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11306. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11307. if (dst->src[s] == src) {
  11308. return true;
  11309. }
  11310. }
  11311. // implicit dependency if they view the same tensor
  11312. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11313. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11314. if (dst2 == src2) {
  11315. return true;
  11316. }
  11317. return false;
  11318. };
  11319. // This function tries to reorder the graph to allow nodes to run in parallel.
  11320. // This helps with small batches, but for large batches its a slowdown, probably
  11321. // due to cache contention. So only reorder if the majority of nodes have few rows.
  11322. int num_small_nodes = 0;
  11323. int num_counted_nodes = 0;
  11324. for (int i = 0; i < graph->n_nodes; ++i) {
  11325. if (!is_empty(graph->nodes[i]) &&
  11326. graph->nodes[i]->op != GGML_OP_SET_ROWS) {
  11327. if (ggml_nrows(graph->nodes[i]) <= 8) {
  11328. num_small_nodes++;
  11329. }
  11330. num_counted_nodes++;
  11331. }
  11332. }
  11333. if (num_small_nodes < num_counted_nodes / 2) {
  11334. return;
  11335. }
  11336. std::vector<ggml_tensor *> new_order;
  11337. std::vector<bool> used(graph->n_nodes, false);
  11338. int first_unused = 0;
  11339. while (first_unused < graph->n_nodes) {
  11340. std::vector<int> current_set;
  11341. // Check for fusion patterns and avoid reordering them
  11342. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11343. if (start + (int)pattern.size() <= graph->n_nodes) {
  11344. bool is_pattern = true;
  11345. for (size_t j = 0; j < pattern.size(); ++j) {
  11346. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11347. is_pattern = false;
  11348. }
  11349. }
  11350. return is_pattern;
  11351. }
  11352. return false;
  11353. };
  11354. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11355. if (match_pattern(pattern, first_unused)) {
  11356. for (size_t j = 0; j < pattern.size(); ++j) {
  11357. new_order.push_back(graph->nodes[first_unused + j]);
  11358. used[first_unused + j] = true;
  11359. }
  11360. while (first_unused < graph->n_nodes && used[first_unused]) {
  11361. first_unused++;
  11362. }
  11363. return true;
  11364. }
  11365. return false;
  11366. };
  11367. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11368. continue;
  11369. }
  11370. if (keep_pattern(topk_moe_early_softmax)) {
  11371. continue;
  11372. }
  11373. if (keep_pattern(topk_moe_late_softmax)) {
  11374. continue;
  11375. }
  11376. // First, grab the next unused node.
  11377. current_set.push_back(first_unused);
  11378. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11379. // haven't already been run. Nodes that have already been run have used[i] set
  11380. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11381. // that we support (e.g. RMS_NORM + MUL).
  11382. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11383. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11384. const int NUM_TO_CHECK = 20;
  11385. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11386. if (used[j]) {
  11387. continue;
  11388. }
  11389. if (is_empty(graph->nodes[j])) {
  11390. continue;
  11391. }
  11392. // Don't pull forward nodes from fusion patterns
  11393. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11394. match_pattern(topk_moe_early_softmax, j) ||
  11395. match_pattern(topk_moe_late_softmax, j)) {
  11396. continue;
  11397. }
  11398. bool ok = true;
  11399. for (int c = first_unused; c < j; ++c) {
  11400. if (!used[c] &&
  11401. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11402. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11403. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11404. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID)) {
  11405. ok = false;
  11406. break;
  11407. }
  11408. }
  11409. if (ok) {
  11410. current_set.push_back(j);
  11411. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11412. if (graph->nodes[j]->op == GGML_OP_ROPE) {
  11413. int view_idx = -1;
  11414. int set_rows_idx = -1;
  11415. for (int k = j+1; k < std::min(j + 10, graph->n_nodes); ++k) {
  11416. if (view_idx == -1 &&
  11417. graph->nodes[k]->op == GGML_OP_VIEW &&
  11418. graph->nodes[k]->src[0] == graph->nodes[j]) {
  11419. view_idx = k;
  11420. continue;
  11421. }
  11422. if (view_idx != -1 &&
  11423. set_rows_idx == -1 &&
  11424. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11425. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11426. set_rows_idx = k;
  11427. break;
  11428. }
  11429. }
  11430. if (set_rows_idx != -1) {
  11431. current_set.push_back(view_idx);
  11432. current_set.push_back(set_rows_idx);
  11433. used[view_idx] = true;
  11434. used[set_rows_idx] = true;
  11435. }
  11436. }
  11437. }
  11438. }
  11439. // Second pass grabs view nodes.
  11440. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11441. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11442. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11443. if (used[j]) {
  11444. continue;
  11445. }
  11446. if (!is_empty(graph->nodes[j])) {
  11447. continue;
  11448. }
  11449. bool ok = true;
  11450. for (int c = first_unused; c < j; ++c) {
  11451. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11452. // skip views whose srcs haven't been processed.
  11453. if (!used[c] &&
  11454. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11455. !c_in_current_set) {
  11456. ok = false;
  11457. break;
  11458. }
  11459. }
  11460. if (ok) {
  11461. current_set.push_back(j);
  11462. }
  11463. }
  11464. }
  11465. // Push the current set into new_order
  11466. for (auto c : current_set) {
  11467. new_order.push_back(graph->nodes[c]);
  11468. used[c] = true;
  11469. }
  11470. while (first_unused < graph->n_nodes && used[first_unused]) {
  11471. first_unused++;
  11472. }
  11473. }
  11474. // Replace the graph with the new order.
  11475. for (int i = 0; i < graph->n_nodes; ++i) {
  11476. graph->nodes[i] = new_order[i];
  11477. }
  11478. }
  11479. // TODO: enable async and synchronize
  11480. static ggml_backend_i ggml_backend_vk_interface = {
  11481. /* .get_name = */ ggml_backend_vk_name,
  11482. /* .free = */ ggml_backend_vk_free,
  11483. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  11484. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  11485. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11486. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  11487. /* .graph_plan_create = */ NULL,
  11488. /* .graph_plan_free = */ NULL,
  11489. /* .graph_plan_update = */ NULL,
  11490. /* .graph_plan_compute = */ NULL,
  11491. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11492. /* .event_record = */ NULL,
  11493. /* .event_wait = */ NULL,
  11494. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11495. };
  11496. static ggml_guid_t ggml_backend_vk_guid() {
  11497. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11498. return &guid;
  11499. }
  11500. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11501. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11502. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11503. ggml_vk_init(ctx, dev_num);
  11504. ggml_backend_t vk_backend = new ggml_backend {
  11505. /* .guid = */ ggml_backend_vk_guid(),
  11506. /* .iface = */ ggml_backend_vk_interface,
  11507. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11508. /* .context = */ ctx,
  11509. };
  11510. return vk_backend;
  11511. }
  11512. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11513. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11514. }
  11515. int ggml_backend_vk_get_device_count() {
  11516. return ggml_vk_get_device_count();
  11517. }
  11518. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11519. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11520. int dev_idx = vk_instance.device_indices[device];
  11521. ggml_vk_get_device_description(dev_idx, description, description_size);
  11522. }
  11523. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11524. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11525. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11526. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11527. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11528. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11529. bool membudget_supported = vk_instance.device_supports_membudget[device];
  11530. if (membudget_supported) {
  11531. memprops.pNext = &budgetprops;
  11532. }
  11533. vkdev.getMemoryProperties2(&memprops);
  11534. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11535. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11536. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  11537. *total = heap.size;
  11538. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11539. *free = budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11540. } else {
  11541. *free = heap.size;
  11542. }
  11543. break;
  11544. }
  11545. }
  11546. }
  11547. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11548. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11549. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11550. vk::PhysicalDeviceProperties2 props = {};
  11551. device.getProperties2(&props);
  11552. return props.properties.deviceType;
  11553. }
  11554. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11555. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11556. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11557. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11558. bool ext_support = false;
  11559. for (const auto& properties : ext_props) {
  11560. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11561. ext_support = true;
  11562. break;
  11563. }
  11564. }
  11565. if (!ext_support) {
  11566. return "";
  11567. }
  11568. vk::PhysicalDeviceProperties2 props = {};
  11569. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11570. props.pNext = &pci_bus_info;
  11571. device.getProperties2(&props);
  11572. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11573. const uint32_t pci_bus = pci_bus_info.pciBus;
  11574. const uint32_t pci_device = pci_bus_info.pciDevice;
  11575. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11576. char pci_bus_id[16] = {};
  11577. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11578. return std::string(pci_bus_id);
  11579. }
  11580. //////////////////////////
  11581. struct ggml_backend_vk_device_context {
  11582. size_t device;
  11583. std::string name;
  11584. std::string description;
  11585. bool is_integrated_gpu;
  11586. std::string pci_bus_id;
  11587. };
  11588. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11589. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11590. return ctx->name.c_str();
  11591. }
  11592. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11593. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11594. return ctx->description.c_str();
  11595. }
  11596. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11597. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11598. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11599. }
  11600. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11601. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11602. return ggml_backend_vk_buffer_type(ctx->device);
  11603. }
  11604. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11605. UNUSED(dev);
  11606. return ggml_backend_vk_host_buffer_type();
  11607. }
  11608. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11609. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11610. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11611. }
  11612. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11613. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11614. props->name = ggml_backend_vk_device_get_name(dev);
  11615. props->description = ggml_backend_vk_device_get_description(dev);
  11616. props->type = ggml_backend_vk_device_get_type(dev);
  11617. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11618. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11619. props->caps = {
  11620. /* .async = */ false,
  11621. /* .host_buffer = */ true,
  11622. /* .buffer_from_host_ptr = */ false,
  11623. /* .events = */ false,
  11624. };
  11625. }
  11626. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11627. UNUSED(params);
  11628. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11629. return ggml_backend_vk_init(ctx->device);
  11630. }
  11631. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11632. switch (op->op) {
  11633. case GGML_OP_UNARY:
  11634. switch (ggml_get_unary_op(op)) {
  11635. case GGML_UNARY_OP_EXP:
  11636. case GGML_UNARY_OP_GELU:
  11637. case GGML_UNARY_OP_GELU_ERF:
  11638. case GGML_UNARY_OP_GELU_QUICK:
  11639. case GGML_UNARY_OP_SILU:
  11640. case GGML_UNARY_OP_RELU:
  11641. case GGML_UNARY_OP_TANH:
  11642. case GGML_UNARY_OP_SIGMOID:
  11643. case GGML_UNARY_OP_HARDSIGMOID:
  11644. case GGML_UNARY_OP_HARDSWISH:
  11645. return ggml_is_contiguous(op->src[0]) &&
  11646. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11647. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11648. (op->src[0]->type == op->type);
  11649. default:
  11650. return false;
  11651. }
  11652. case GGML_OP_GLU:
  11653. switch (ggml_get_glu_op(op)) {
  11654. case GGML_GLU_OP_GEGLU:
  11655. case GGML_GLU_OP_REGLU:
  11656. case GGML_GLU_OP_SWIGLU:
  11657. case GGML_GLU_OP_SWIGLU_OAI:
  11658. case GGML_GLU_OP_GEGLU_ERF:
  11659. case GGML_GLU_OP_GEGLU_QUICK:
  11660. return ggml_is_contiguous(op->src[0]) &&
  11661. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11662. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11663. (op->src[0]->type == op->type);
  11664. default:
  11665. return false;
  11666. }
  11667. case GGML_OP_MUL_MAT:
  11668. case GGML_OP_MUL_MAT_ID:
  11669. {
  11670. ggml_type src0_type = op->src[0]->type;
  11671. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11672. const vk_device& device = ggml_vk_get_device(ctx->device);
  11673. if (op->op == GGML_OP_MUL_MAT_ID) {
  11674. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11675. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11676. return false;
  11677. }
  11678. }
  11679. switch (src0_type) {
  11680. case GGML_TYPE_F32:
  11681. case GGML_TYPE_F16:
  11682. case GGML_TYPE_BF16:
  11683. case GGML_TYPE_Q4_0:
  11684. case GGML_TYPE_Q4_1:
  11685. case GGML_TYPE_Q5_0:
  11686. case GGML_TYPE_Q5_1:
  11687. case GGML_TYPE_Q8_0:
  11688. case GGML_TYPE_Q2_K:
  11689. case GGML_TYPE_Q3_K:
  11690. case GGML_TYPE_Q4_K:
  11691. case GGML_TYPE_Q5_K:
  11692. case GGML_TYPE_Q6_K:
  11693. case GGML_TYPE_IQ1_S:
  11694. case GGML_TYPE_IQ1_M:
  11695. case GGML_TYPE_IQ2_XXS:
  11696. case GGML_TYPE_IQ2_XS:
  11697. case GGML_TYPE_IQ2_S:
  11698. case GGML_TYPE_IQ3_XXS:
  11699. case GGML_TYPE_IQ3_S:
  11700. case GGML_TYPE_IQ4_XS:
  11701. case GGML_TYPE_IQ4_NL:
  11702. case GGML_TYPE_MXFP4:
  11703. break;
  11704. default:
  11705. return false;
  11706. }
  11707. struct ggml_tensor * a;
  11708. struct ggml_tensor * b;
  11709. if (op->op == GGML_OP_MUL_MAT) {
  11710. a = op->src[0];
  11711. b = op->src[1];
  11712. } else {
  11713. a = op->src[2];
  11714. b = op->src[1];
  11715. }
  11716. if (a->ne[3] != b->ne[3]) {
  11717. return false;
  11718. }
  11719. 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) ||
  11720. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  11721. return false;
  11722. }
  11723. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  11724. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  11725. // So don't support this combination for now.
  11726. return false;
  11727. }
  11728. return true;
  11729. }
  11730. case GGML_OP_FLASH_ATTN_EXT:
  11731. {
  11732. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11733. auto device = ggml_vk_get_device(ctx->device);
  11734. bool coopmat2 = device->coopmat2;
  11735. uint32_t HSK = op->src[1]->ne[0];
  11736. uint32_t HSV = op->src[2]->ne[0];
  11737. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  11738. return false;
  11739. }
  11740. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  11741. return false;
  11742. }
  11743. if (op->src[0]->type != GGML_TYPE_F32) {
  11744. return false;
  11745. }
  11746. if (op->type != GGML_TYPE_F32) {
  11747. return false;
  11748. }
  11749. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  11750. return false;
  11751. }
  11752. // It's straightforward to support different K/V dequant, but would
  11753. // significantly increase the number of pipelines
  11754. if (op->src[1]->type != op->src[2]->type) {
  11755. return false;
  11756. }
  11757. switch (op->src[1]->type) {
  11758. case GGML_TYPE_F16:
  11759. case GGML_TYPE_F32:
  11760. case GGML_TYPE_Q4_0:
  11761. case GGML_TYPE_Q8_0:
  11762. // supported in scalar and coopmat2 paths
  11763. break;
  11764. case GGML_TYPE_Q4_1:
  11765. case GGML_TYPE_Q5_0:
  11766. case GGML_TYPE_Q5_1:
  11767. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  11768. //case GGML_TYPE_Q2_K:
  11769. //case GGML_TYPE_Q3_K:
  11770. //case GGML_TYPE_Q4_K:
  11771. //case GGML_TYPE_Q5_K:
  11772. //case GGML_TYPE_Q6_K:
  11773. //case GGML_TYPE_IQ1_S:
  11774. //case GGML_TYPE_IQ1_M:
  11775. //case GGML_TYPE_IQ2_XXS:
  11776. //case GGML_TYPE_IQ2_XS:
  11777. //case GGML_TYPE_IQ2_S:
  11778. //case GGML_TYPE_IQ3_XXS:
  11779. //case GGML_TYPE_IQ3_S:
  11780. //case GGML_TYPE_IQ4_XS:
  11781. case GGML_TYPE_IQ4_NL:
  11782. // currently supported only in coopmat2 path
  11783. if (!coopmat2) {
  11784. return false;
  11785. }
  11786. break;
  11787. default:
  11788. return false;
  11789. }
  11790. if (!coopmat2 && !device->subgroup_shuffle) {
  11791. // scalar FA uses subgroupShuffle
  11792. return false;
  11793. }
  11794. return true;
  11795. }
  11796. case GGML_OP_GET_ROWS:
  11797. {
  11798. switch (op->src[0]->type) {
  11799. case GGML_TYPE_F32:
  11800. case GGML_TYPE_F16:
  11801. case GGML_TYPE_BF16:
  11802. case GGML_TYPE_Q4_0:
  11803. case GGML_TYPE_Q4_1:
  11804. case GGML_TYPE_Q5_0:
  11805. case GGML_TYPE_Q5_1:
  11806. case GGML_TYPE_Q8_0:
  11807. case GGML_TYPE_Q2_K:
  11808. case GGML_TYPE_Q3_K:
  11809. case GGML_TYPE_Q4_K:
  11810. case GGML_TYPE_Q5_K:
  11811. case GGML_TYPE_Q6_K:
  11812. case GGML_TYPE_IQ1_S:
  11813. case GGML_TYPE_IQ1_M:
  11814. case GGML_TYPE_IQ2_XXS:
  11815. case GGML_TYPE_IQ2_XS:
  11816. case GGML_TYPE_IQ2_S:
  11817. case GGML_TYPE_IQ3_XXS:
  11818. case GGML_TYPE_IQ3_S:
  11819. case GGML_TYPE_IQ4_XS:
  11820. case GGML_TYPE_IQ4_NL:
  11821. case GGML_TYPE_MXFP4:
  11822. return true;
  11823. default:
  11824. return false;
  11825. }
  11826. }
  11827. case GGML_OP_SET_ROWS:
  11828. {
  11829. switch (op->type) {
  11830. case GGML_TYPE_F32:
  11831. case GGML_TYPE_F16:
  11832. case GGML_TYPE_BF16:
  11833. case GGML_TYPE_Q4_0:
  11834. case GGML_TYPE_Q4_1:
  11835. case GGML_TYPE_Q5_0:
  11836. case GGML_TYPE_Q5_1:
  11837. case GGML_TYPE_Q8_0:
  11838. case GGML_TYPE_IQ4_NL:
  11839. return true;
  11840. default:
  11841. return false;
  11842. }
  11843. }
  11844. case GGML_OP_CONT:
  11845. case GGML_OP_CPY:
  11846. case GGML_OP_DUP:
  11847. {
  11848. ggml_type src0_type = op->src[0]->type;
  11849. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  11850. if (src0_type == GGML_TYPE_F32) {
  11851. switch (src1_type) {
  11852. case GGML_TYPE_F32:
  11853. case GGML_TYPE_F16:
  11854. case GGML_TYPE_BF16:
  11855. case GGML_TYPE_Q4_0:
  11856. case GGML_TYPE_Q4_1:
  11857. case GGML_TYPE_Q5_0:
  11858. case GGML_TYPE_Q5_1:
  11859. case GGML_TYPE_Q8_0:
  11860. case GGML_TYPE_IQ4_NL:
  11861. return true;
  11862. default:
  11863. break;
  11864. }
  11865. }
  11866. if (src1_type == GGML_TYPE_F32) {
  11867. switch (src0_type) {
  11868. case GGML_TYPE_F16:
  11869. case GGML_TYPE_Q4_0:
  11870. case GGML_TYPE_Q4_1:
  11871. case GGML_TYPE_Q5_0:
  11872. case GGML_TYPE_Q5_1:
  11873. case GGML_TYPE_Q8_0:
  11874. case GGML_TYPE_IQ4_NL:
  11875. return true;
  11876. default:
  11877. break;
  11878. }
  11879. }
  11880. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  11881. return true;
  11882. }
  11883. if (
  11884. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  11885. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  11886. ) {
  11887. return true;
  11888. }
  11889. // We can handle copying from a type to the same type if it's
  11890. // contiguous (memcpy). We use f16 or f32 shaders to do the copy,
  11891. // so the type/block size must be a multiple of 4.
  11892. if (src0_type == src1_type &&
  11893. ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) &&
  11894. (ggml_type_size(src0_type) % 2) == 0) {
  11895. return true;
  11896. }
  11897. return false;
  11898. }
  11899. case GGML_OP_REPEAT:
  11900. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  11901. case GGML_OP_REPEAT_BACK:
  11902. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  11903. case GGML_OP_ROPE:
  11904. case GGML_OP_ROPE_BACK:
  11905. case GGML_OP_NONE:
  11906. case GGML_OP_RESHAPE:
  11907. case GGML_OP_VIEW:
  11908. case GGML_OP_PERMUTE:
  11909. case GGML_OP_TRANSPOSE:
  11910. case GGML_OP_RMS_NORM:
  11911. return true;
  11912. case GGML_OP_NORM:
  11913. case GGML_OP_GROUP_NORM:
  11914. case GGML_OP_L2_NORM:
  11915. return ggml_is_contiguous(op->src[0]);
  11916. case GGML_OP_ADD:
  11917. case GGML_OP_SUB:
  11918. case GGML_OP_MUL:
  11919. case GGML_OP_DIV:
  11920. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11921. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  11922. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  11923. case GGML_OP_ADD_ID:
  11924. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  11925. op->type == GGML_TYPE_F32;
  11926. case GGML_OP_SILU_BACK:
  11927. case GGML_OP_RMS_NORM_BACK:
  11928. case GGML_OP_SQR:
  11929. case GGML_OP_SQRT:
  11930. case GGML_OP_SIN:
  11931. case GGML_OP_COS:
  11932. case GGML_OP_CLAMP:
  11933. case GGML_OP_LEAKY_RELU:
  11934. case GGML_OP_OPT_STEP_ADAMW:
  11935. case GGML_OP_OPT_STEP_SGD:
  11936. return op->src[0]->type == GGML_TYPE_F32;
  11937. case GGML_OP_ARGSORT:
  11938. return op->ne[0] <= max_argsort_cols;
  11939. case GGML_OP_UPSCALE:
  11940. case GGML_OP_ACC:
  11941. case GGML_OP_CONCAT:
  11942. case GGML_OP_SCALE:
  11943. case GGML_OP_PAD:
  11944. case GGML_OP_ROLL:
  11945. case GGML_OP_DIAG_MASK_INF:
  11946. case GGML_OP_SOFT_MAX:
  11947. case GGML_OP_SOFT_MAX_BACK:
  11948. return true;
  11949. case GGML_OP_SUM:
  11950. case GGML_OP_SUM_ROWS:
  11951. case GGML_OP_MEAN:
  11952. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  11953. case GGML_OP_ARGMAX:
  11954. case GGML_OP_COUNT_EQUAL:
  11955. case GGML_OP_IM2COL:
  11956. case GGML_OP_IM2COL_3D:
  11957. case GGML_OP_TIMESTEP_EMBEDDING:
  11958. case GGML_OP_CONV_2D_DW:
  11959. case GGML_OP_POOL_2D:
  11960. case GGML_OP_RWKV_WKV6:
  11961. case GGML_OP_RWKV_WKV7:
  11962. return true;
  11963. case GGML_OP_SSM_SCAN:
  11964. {
  11965. for (int i = 0; i < 6; i++) {
  11966. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  11967. return false;
  11968. }
  11969. }
  11970. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  11971. return false;
  11972. }
  11973. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  11974. return false;
  11975. }
  11976. const uint32_t d_state = op->src[0]->ne[0];
  11977. const uint32_t head_dim = op->src[0]->ne[1];
  11978. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  11979. if (!is_mamba2) {
  11980. return false;
  11981. }
  11982. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  11983. return false;
  11984. }
  11985. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11986. const vk_device& device = ggml_vk_get_device(ctx->device);
  11987. const uint32_t SPLIT_H = 16;
  11988. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  11989. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  11990. return false;
  11991. }
  11992. return true;
  11993. }
  11994. case GGML_OP_SSM_CONV:
  11995. return true;
  11996. case GGML_OP_CONV_TRANSPOSE_1D:
  11997. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  11998. case GGML_OP_CONV_2D:
  11999. case GGML_OP_CONV_TRANSPOSE_2D:
  12000. {
  12001. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  12002. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12003. const vk_device& device = ggml_vk_get_device(ctx->device);
  12004. if (op->op == GGML_OP_CONV_TRANSPOSE_2D &&
  12005. device->properties.limits.maxPushConstantsSize < sizeof(vk_op_conv_transpose_2d_push_constants)) {
  12006. return false;
  12007. }
  12008. // Channel-contiguous format is not supported yet.
  12009. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12010. op->src[1]->type == GGML_TYPE_F32 &&
  12011. op->type == GGML_TYPE_F32 &&
  12012. ggml_is_contiguous(op->src[0]) &&
  12013. ggml_is_contiguous(op->src[1]) &&
  12014. ggml_is_contiguous(op));
  12015. }
  12016. default:
  12017. return false;
  12018. }
  12019. UNUSED(dev);
  12020. }
  12021. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  12022. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  12023. return false;
  12024. }
  12025. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12026. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  12027. return buft_ctx->device->idx == ctx->device;
  12028. }
  12029. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12030. const int min_batch_size = 32;
  12031. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  12032. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  12033. UNUSED(dev);
  12034. }
  12035. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  12036. /* .get_name = */ ggml_backend_vk_device_get_name,
  12037. /* .get_description = */ ggml_backend_vk_device_get_description,
  12038. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  12039. /* .get_type = */ ggml_backend_vk_device_get_type,
  12040. /* .get_props = */ ggml_backend_vk_device_get_props,
  12041. /* .init_backend = */ ggml_backend_vk_device_init,
  12042. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  12043. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  12044. /* .buffer_from_host_ptr = */ NULL,
  12045. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  12046. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  12047. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  12048. /* .event_new = */ NULL,
  12049. /* .event_free = */ NULL,
  12050. /* .event_synchronize = */ NULL,
  12051. };
  12052. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  12053. UNUSED(reg);
  12054. return GGML_VK_NAME;
  12055. }
  12056. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  12057. UNUSED(reg);
  12058. return ggml_backend_vk_get_device_count();
  12059. }
  12060. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  12061. static std::vector<ggml_backend_dev_t> devices;
  12062. static bool initialized = false;
  12063. {
  12064. static std::mutex mutex;
  12065. std::lock_guard<std::mutex> lock(mutex);
  12066. if (!initialized) {
  12067. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  12068. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  12069. char desc[256];
  12070. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  12071. ctx->device = i;
  12072. ctx->name = GGML_VK_NAME + std::to_string(i);
  12073. ctx->description = desc;
  12074. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  12075. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  12076. devices.push_back(new ggml_backend_device {
  12077. /* .iface = */ ggml_backend_vk_device_i,
  12078. /* .reg = */ reg,
  12079. /* .context = */ ctx,
  12080. });
  12081. }
  12082. initialized = true;
  12083. }
  12084. }
  12085. GGML_ASSERT(device < devices.size());
  12086. return devices[device];
  12087. }
  12088. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  12089. /* .get_name = */ ggml_backend_vk_reg_get_name,
  12090. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  12091. /* .get_device = */ ggml_backend_vk_reg_get_device,
  12092. /* .get_proc_address = */ NULL,
  12093. };
  12094. ggml_backend_reg_t ggml_backend_vk_reg() {
  12095. static ggml_backend_reg reg = {
  12096. /* .api_version = */ GGML_BACKEND_API_VERSION,
  12097. /* .iface = */ ggml_backend_vk_reg_i,
  12098. /* .context = */ nullptr,
  12099. };
  12100. try {
  12101. ggml_vk_instance_init();
  12102. return &reg;
  12103. } catch (const vk::SystemError& e) {
  12104. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  12105. return nullptr;
  12106. } catch (const std::exception &e) {
  12107. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  12108. return nullptr;
  12109. } catch (...) {
  12110. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  12111. return nullptr;
  12112. }
  12113. }
  12114. // Extension availability
  12115. static bool ggml_vk_instance_validation_ext_available() {
  12116. #ifdef GGML_VULKAN_VALIDATE
  12117. // Check if validation layer provides the extension
  12118. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  12119. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  12120. if (layer_name == layer.layerName.data()) {
  12121. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  12122. if (strcmp("VK_EXT_validation_features", ext.extensionName.data()) == 0) {
  12123. return true;
  12124. }
  12125. }
  12126. }
  12127. }
  12128. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_validation_features not found." << std::endl;
  12129. #endif
  12130. return false;
  12131. }
  12132. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  12133. #ifdef __APPLE__
  12134. // Check for portability enumeration extension for MoltenVK support
  12135. for (const auto& properties : instance_extensions) {
  12136. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  12137. return true;
  12138. }
  12139. }
  12140. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  12141. #endif
  12142. return false;
  12143. UNUSED(instance_extensions);
  12144. }
  12145. // Extension availability
  12146. static bool ggml_vk_instance_debug_utils_ext_available(
  12147. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  12148. // Check for portability enumeration extension for MoltenVK support
  12149. for (const auto & properties : instance_extensions) {
  12150. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  12151. return true;
  12152. }
  12153. }
  12154. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  12155. return false;
  12156. UNUSED(instance_extensions);
  12157. }
  12158. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  12159. VkPhysicalDeviceFeatures2 device_features2;
  12160. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  12161. VkPhysicalDeviceVulkan11Features vk11_features;
  12162. vk11_features.pNext = nullptr;
  12163. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  12164. device_features2.pNext = &vk11_features;
  12165. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  12166. return vk11_features.storageBuffer16BitAccess;
  12167. }
  12168. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  12169. switch (props.vendorID) {
  12170. case VK_VENDOR_ID_INTEL:
  12171. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  12172. // while some older hardware (ex. Arc A770) has performance regressions
  12173. return arch == vk_device_architecture::INTEL_XE2;
  12174. case VK_VENDOR_ID_AMD:
  12175. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  12176. // Workaround for AMD proprietary driver reporting support on all GPUs
  12177. return arch == vk_device_architecture::AMD_RDNA3;
  12178. }
  12179. return true;
  12180. default:
  12181. return true;
  12182. }
  12183. }
  12184. // checks
  12185. #ifdef GGML_VULKAN_CHECK_RESULTS
  12186. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  12187. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  12188. return;
  12189. }
  12190. for (int j = 0; j < level; j++) {
  12191. std::cerr << " ";
  12192. }
  12193. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  12194. done.push_back(tensor);
  12195. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12196. if (tensor->src[i] != nullptr) {
  12197. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  12198. }
  12199. }
  12200. }
  12201. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  12202. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  12203. return;
  12204. }
  12205. i0 = std::max(i0, 5);
  12206. i1 = std::max(i1, 5);
  12207. i2 = std::max(i2, 0);
  12208. i3 = std::max(i3, 0);
  12209. fprintf(stderr, " ");
  12210. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12211. fprintf(stderr, "%7d ", idx1);
  12212. }
  12213. fprintf(stderr, "\n");
  12214. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12215. fprintf(stderr, "%7d: ", idx0);
  12216. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12217. 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]) {
  12218. float val;
  12219. if (tensor->type == GGML_TYPE_F32) {
  12220. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12221. } else if (tensor->type == GGML_TYPE_F16) {
  12222. 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]));
  12223. } else if (tensor->type == GGML_TYPE_I32) {
  12224. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12225. } else {
  12226. GGML_ABORT("fatal error");
  12227. }
  12228. fprintf(stderr, "% 7.2f ", val);
  12229. } else {
  12230. fprintf(stderr, " ");
  12231. }
  12232. }
  12233. fprintf(stderr, "\n");
  12234. }
  12235. }
  12236. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  12237. void * tensor_data = tensor->data;
  12238. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  12239. if (is_gpu) {
  12240. const size_t tensor_size = ggml_nbytes(tensor);
  12241. tensor_data = malloc(tensor_size);
  12242. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12243. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  12244. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  12245. }
  12246. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  12247. 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;
  12248. if (tensor->src[0] != nullptr) {
  12249. 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;
  12250. }
  12251. if (tensor->src[1] != nullptr) {
  12252. 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;
  12253. }
  12254. std::cerr << std::endl << "Result:" << std::endl;
  12255. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12256. std::cerr << std::endl;
  12257. std::vector<const ggml_tensor *> done;
  12258. ggml_vk_print_graph_origin(tensor, done);
  12259. if (is_gpu) {
  12260. free(tensor_data);
  12261. }
  12262. }
  12263. void * comp_result;
  12264. size_t comp_size;
  12265. size_t comp_nb[GGML_MAX_DIMS];
  12266. size_t check_counter = 0;
  12267. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12268. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  12269. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12270. return;
  12271. }
  12272. bool fused_rms_norm_mul = false;
  12273. int rms_norm_idx = -1;
  12274. if (ctx->num_additional_fused_ops == 1 &&
  12275. tensor->op == GGML_OP_RMS_NORM &&
  12276. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  12277. fused_rms_norm_mul = true;
  12278. tensor = cgraph->nodes[tensor_idx + 1];
  12279. }
  12280. check_counter++;
  12281. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12282. return;
  12283. }
  12284. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12285. ggml_tensor * src0 = tensor->src[0];
  12286. ggml_tensor * src1 = tensor->src[1];
  12287. struct ggml_init_params iparams = {
  12288. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12289. /*.mem_buffer =*/ NULL,
  12290. /*.no_alloc =*/ false,
  12291. };
  12292. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12293. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12294. std::array<size_t, GGML_MAX_SRC> src_size = {};
  12295. std::array<void *, GGML_MAX_SRC> src_buffer = {};
  12296. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12297. struct ggml_tensor * tensor_clone = nullptr;
  12298. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12299. ggml_tensor * srci = tensor->src[i];
  12300. if (fused_rms_norm_mul) {
  12301. rms_norm_idx = tensor->src[0]->op == GGML_OP_RMS_NORM ? 0 : 1;
  12302. ggml_tensor *rms_norm = tensor->src[rms_norm_idx];
  12303. switch (i) {
  12304. case 0: srci = rms_norm->src[0]; break;
  12305. case 1: srci = tensor->src[1 - rms_norm_idx]; break;
  12306. default: continue;
  12307. }
  12308. }
  12309. if (srci == nullptr) {
  12310. continue;
  12311. }
  12312. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12313. size_t srci_size = ggml_nbytes(srci);
  12314. src_clone[i] = srci_clone;
  12315. src_size[i] = ggml_nbytes(srci);
  12316. src_buffer[i] = malloc(srci_size);
  12317. srci_clone->data = src_buffer[i];
  12318. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12319. memcpy(srci_clone->data, srci->data, srci_size);
  12320. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12321. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12322. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12323. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12324. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12325. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12326. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12327. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12328. const int idx = i3*srci->ne[2] + i2;
  12329. 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]);
  12330. }
  12331. }
  12332. srci_clone->nb[0] = srci->nb[0];
  12333. srci_clone->nb[1] = srci->nb[1];
  12334. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12335. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12336. }
  12337. } else {
  12338. if (offset + srci_size >= buffer_gpu->size) {
  12339. srci_size = buffer_gpu->size - offset;
  12340. }
  12341. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12342. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12343. }
  12344. } else {
  12345. GGML_ABORT("fatal error");
  12346. }
  12347. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12348. ggml_vk_print_tensor(srci, srci_name[i]);
  12349. }
  12350. }
  12351. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12352. const float * params = (const float *)tensor->op_params;
  12353. 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]);
  12354. if (src_clone[4]) {
  12355. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12356. }
  12357. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12358. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12359. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12360. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12361. } else if (tensor->op == GGML_OP_SUB) {
  12362. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12363. } else if (tensor->op == GGML_OP_MUL) {
  12364. if (fused_rms_norm_mul) {
  12365. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->src[rms_norm_idx]->op_params);
  12366. tensor_clone = ggml_mul(ggml_ctx, tensor_clone, src_clone[1 - rms_norm_idx]);
  12367. } else {
  12368. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12369. }
  12370. } else if (tensor->op == GGML_OP_DIV) {
  12371. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12372. } else if (tensor->op == GGML_OP_CONCAT) {
  12373. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12374. } else if (tensor->op == GGML_OP_UPSCALE) {
  12375. 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]);
  12376. } else if (tensor->op == GGML_OP_SCALE) {
  12377. const float * params = (const float *)tensor->op_params;
  12378. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12379. } else if (tensor->op == GGML_OP_SQR) {
  12380. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12381. } else if (tensor->op == GGML_OP_SQRT) {
  12382. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12383. } else if (tensor->op == GGML_OP_SIN) {
  12384. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12385. } else if (tensor->op == GGML_OP_COS) {
  12386. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12387. } else if (tensor->op == GGML_OP_CLAMP) {
  12388. const float * params = (const float *)tensor->op_params;
  12389. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12390. } else if (tensor->op == GGML_OP_PAD) {
  12391. 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],
  12392. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12393. } else if (tensor->op == GGML_OP_REPEAT) {
  12394. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12395. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12396. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12397. } else if (tensor->op == GGML_OP_ADD) {
  12398. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12399. } else if (tensor->op == GGML_OP_ACC) {
  12400. 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]);
  12401. } else if (tensor->op == GGML_OP_NORM) {
  12402. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12403. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12404. const float * float_params = (const float *)tensor->op_params;
  12405. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12406. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12407. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12408. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12409. const float eps = ((float *) tensor->op_params)[0];
  12410. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12411. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12412. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12413. } else if (tensor->op == GGML_OP_L2_NORM) {
  12414. const float eps = ((float *) tensor->op_params)[0];
  12415. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12416. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12417. if (src1 != nullptr) {
  12418. const float * params = (const float *)tensor->op_params;
  12419. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12420. } else {
  12421. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12422. }
  12423. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12424. 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]);
  12425. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12426. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12427. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12428. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12429. const int mode = ((int32_t *) tensor->op_params)[2];
  12430. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12431. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12432. const float freq_base = ((float *) tensor->op_params)[5];
  12433. const float freq_scale = ((float *) tensor->op_params)[6];
  12434. const float ext_factor = ((float *) tensor->op_params)[7];
  12435. const float attn_factor = ((float *) tensor->op_params)[8];
  12436. const float beta_fast = ((float *) tensor->op_params)[9];
  12437. const float beta_slow = ((float *) tensor->op_params)[10];
  12438. if (mode & GGML_ROPE_TYPE_MROPE) {
  12439. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12440. if (tensor->op == GGML_OP_ROPE) {
  12441. 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);
  12442. } else {
  12443. 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);
  12444. }
  12445. } else {
  12446. if (tensor->op == GGML_OP_ROPE) {
  12447. 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);
  12448. } else {
  12449. 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);
  12450. }
  12451. }
  12452. } else if (tensor->op == GGML_OP_UNARY) {
  12453. switch (ggml_get_unary_op(tensor)) {
  12454. case GGML_UNARY_OP_EXP:
  12455. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12456. break;
  12457. case GGML_UNARY_OP_SILU:
  12458. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12459. break;
  12460. case GGML_UNARY_OP_GELU:
  12461. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12462. break;
  12463. case GGML_UNARY_OP_GELU_ERF:
  12464. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12465. break;
  12466. case GGML_UNARY_OP_GELU_QUICK:
  12467. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12468. break;
  12469. case GGML_UNARY_OP_RELU:
  12470. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12471. break;
  12472. case GGML_UNARY_OP_TANH:
  12473. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12474. break;
  12475. case GGML_UNARY_OP_SIGMOID:
  12476. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12477. break;
  12478. case GGML_UNARY_OP_HARDSIGMOID:
  12479. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12480. break;
  12481. case GGML_UNARY_OP_HARDSWISH:
  12482. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12483. break;
  12484. default:
  12485. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12486. GGML_ABORT("fatal error");
  12487. }
  12488. } else if (tensor->op == GGML_OP_GLU) {
  12489. if (src_clone[1] == nullptr) {
  12490. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12491. } else {
  12492. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12493. }
  12494. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12495. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12496. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12497. if (src1 == nullptr) {
  12498. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12499. tensor_clone->type = tensor->type;
  12500. } else {
  12501. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12502. }
  12503. } else if (tensor->op == GGML_OP_CONT) {
  12504. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12505. } else if (tensor->op == GGML_OP_RESHAPE) {
  12506. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12507. } else if (tensor->op == GGML_OP_VIEW) {
  12508. 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]);
  12509. } else if (tensor->op == GGML_OP_PERMUTE) {
  12510. int32_t * params = (int32_t *)tensor->op_params;
  12511. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12512. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12513. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12514. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12515. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12516. } else if (tensor->op == GGML_OP_ARGSORT) {
  12517. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12518. } else if (tensor->op == GGML_OP_SUM) {
  12519. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12520. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12521. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12522. } else if (tensor->op == GGML_OP_MEAN) {
  12523. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  12524. } else if (tensor->op == GGML_OP_ARGMAX) {
  12525. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  12526. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  12527. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  12528. } else if (tensor->op == GGML_OP_IM2COL) {
  12529. const int32_t s0 = tensor->op_params[0];
  12530. const int32_t s1 = tensor->op_params[1];
  12531. const int32_t p0 = tensor->op_params[2];
  12532. const int32_t p1 = tensor->op_params[3];
  12533. const int32_t d0 = tensor->op_params[4];
  12534. const int32_t d1 = tensor->op_params[5];
  12535. const bool is_2D = tensor->op_params[6] == 1;
  12536. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  12537. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  12538. const int32_t s0 = tensor->op_params[0];
  12539. const int32_t s1 = tensor->op_params[1];
  12540. const int32_t s2 = tensor->op_params[2];
  12541. const int32_t p0 = tensor->op_params[3];
  12542. const int32_t p1 = tensor->op_params[4];
  12543. const int32_t p2 = tensor->op_params[5];
  12544. const int32_t d0 = tensor->op_params[6];
  12545. const int32_t d1 = tensor->op_params[7];
  12546. const int32_t d2 = tensor->op_params[8];
  12547. const int32_t IC = tensor->op_params[9];
  12548. 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);
  12549. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  12550. const int32_t dim = tensor->op_params[0];
  12551. const int32_t max_period = tensor->op_params[1];
  12552. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  12553. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  12554. const int32_t s0 = tensor->op_params[0];
  12555. const int32_t p0 = tensor->op_params[1];
  12556. const int32_t d0 = tensor->op_params[2];
  12557. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  12558. } else if (tensor->op == GGML_OP_POOL_2D) {
  12559. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  12560. const int32_t k0 = tensor->op_params[1];
  12561. const int32_t k1 = tensor->op_params[2];
  12562. const int32_t s0 = tensor->op_params[3];
  12563. const int32_t s1 = tensor->op_params[4];
  12564. const int32_t p0 = tensor->op_params[5];
  12565. const int32_t p1 = tensor->op_params[6];
  12566. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  12567. } else if (tensor->op == GGML_OP_CONV_2D) {
  12568. const int32_t s0 = tensor->op_params[0];
  12569. const int32_t s1 = tensor->op_params[1];
  12570. const int32_t p0 = tensor->op_params[2];
  12571. const int32_t p1 = tensor->op_params[3];
  12572. const int32_t d0 = tensor->op_params[4];
  12573. const int32_t d1 = tensor->op_params[5];
  12574. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12575. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  12576. const int32_t s = tensor->op_params[0];
  12577. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  12578. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  12579. const float * op_params = (const float *)tensor->op_params;
  12580. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  12581. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  12582. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  12583. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  12584. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  12585. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  12586. src_clone[4], src_clone[5], src_clone[6]);
  12587. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  12588. src_clone[0]->flags = src0->flags;
  12589. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  12590. src_clone[2], src_clone[3], src_clone[4]);
  12591. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  12592. src_clone[0]->flags = src0->flags;
  12593. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  12594. src_clone[2]);
  12595. } else if (tensor->op == GGML_OP_ADD_ID) {
  12596. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12597. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  12598. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  12599. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  12600. } else if (tensor->op == GGML_OP_SSM_CONV) {
  12601. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  12602. }
  12603. else {
  12604. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12605. GGML_ABORT("fatal error");
  12606. }
  12607. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  12608. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  12609. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  12610. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12611. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  12612. }
  12613. comp_size = ggml_nbytes(tensor_clone);
  12614. comp_result = malloc(comp_size);
  12615. memcpy(comp_result, tensor_clone->data, comp_size);
  12616. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12617. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12618. if (src_buffer[i] != nullptr) {
  12619. free(src_buffer[i]);
  12620. }
  12621. }
  12622. ggml_free(ggml_ctx);
  12623. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  12624. }
  12625. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12626. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  12627. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12628. return;
  12629. }
  12630. if (ctx->num_additional_fused_ops == 1 &&
  12631. tensor->op == GGML_OP_RMS_NORM &&
  12632. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  12633. tensor = cgraph->nodes[tensor_idx + 1];
  12634. }
  12635. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12636. return;
  12637. }
  12638. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  12639. ggml_tensor * src0 = tensor->src[0];
  12640. ggml_tensor * src1 = tensor->src[1];
  12641. ggml_tensor * src2 = tensor->src[2];
  12642. ggml_tensor * src3 = tensor->src[3];
  12643. void * tensor_data = tensor->data;
  12644. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12645. size_t tensor_size = ggml_nbytes(tensor);
  12646. tensor_data = malloc(tensor_size);
  12647. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12648. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12649. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  12650. if (offset + tensor_size >= buffer_gpu->size) {
  12651. tensor_size = buffer_gpu->size - offset;
  12652. }
  12653. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  12654. }
  12655. float first_error_result = -1.0f;
  12656. float first_error_correct = -1.0f;
  12657. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  12658. double avg_err = 0.0;
  12659. size_t counter = 0;
  12660. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  12661. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  12662. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  12663. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  12664. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  12665. float correct = 0.0f;
  12666. float result = 0.0f;
  12667. if (buffer_size_fit) {
  12668. if (tensor->type == GGML_TYPE_F32) {
  12669. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12670. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12671. } else if (tensor->type == GGML_TYPE_F16) {
  12672. 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]));
  12673. 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]));
  12674. } else if (tensor->type == GGML_TYPE_BF16) {
  12675. 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]));
  12676. 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]));
  12677. } else if (tensor->type == GGML_TYPE_I32) {
  12678. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12679. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12680. } else if (tensor->type == GGML_TYPE_I64) {
  12681. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12682. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12683. } else {
  12684. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  12685. }
  12686. } else {
  12687. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  12688. GGML_ABORT("fatal error");
  12689. }
  12690. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  12691. 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;
  12692. 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;
  12693. if (src0 != nullptr) {
  12694. 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;
  12695. }
  12696. if (src1 != nullptr) {
  12697. 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;
  12698. }
  12699. if (src2 != nullptr) {
  12700. 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;
  12701. }
  12702. if (src3 != nullptr) {
  12703. 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;
  12704. }
  12705. 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;
  12706. std::cerr << std::endl << "Result:" << std::endl;
  12707. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  12708. std::cerr << std::endl << "Correct:" << std::endl;
  12709. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  12710. std::cerr << std::endl;
  12711. std::vector<const ggml_tensor *> done;
  12712. ggml_vk_print_graph_origin(tensor, done);
  12713. GGML_ABORT("fatal error");
  12714. }
  12715. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  12716. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  12717. first_error[0] = i0;
  12718. first_error[1] = i1;
  12719. first_error[2] = i2;
  12720. first_error[3] = i3;
  12721. first_error_result = result;
  12722. first_error_correct = correct;
  12723. }
  12724. // Special case, value is infinite, avoid NaN result in avg_err
  12725. // NaN also appears in results, if both are nan error is 0
  12726. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  12727. avg_err += std::fabs(correct - result) / denom;
  12728. }
  12729. counter++;
  12730. }
  12731. }
  12732. }
  12733. }
  12734. avg_err /= counter;
  12735. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12736. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12737. 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;
  12738. if (src0 != nullptr) {
  12739. 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;
  12740. }
  12741. if (src1 != nullptr) {
  12742. 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;
  12743. }
  12744. if (src2 != nullptr) {
  12745. 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;
  12746. }
  12747. if (src3 != nullptr) {
  12748. 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;
  12749. }
  12750. 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;
  12751. std::cerr << std::endl << "Result:" << std::endl;
  12752. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12753. std::cerr << std::endl << "Correct:" << std::endl;
  12754. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  12755. std::cerr << std::endl;
  12756. std::vector<const ggml_tensor *> done;
  12757. ggml_vk_print_graph_origin(tensor, done);
  12758. }
  12759. if (avg_err > 0.5 || std::isnan(avg_err)) {
  12760. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12761. 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;
  12762. if (src0 != nullptr) {
  12763. 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;
  12764. }
  12765. if (src1 != nullptr) {
  12766. 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;
  12767. }
  12768. if (src2 != nullptr) {
  12769. 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;
  12770. }
  12771. if (src3 != nullptr) {
  12772. 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;
  12773. }
  12774. 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;
  12775. std::cerr << std::endl << "Result:" << std::endl;
  12776. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  12777. std::cerr << std::endl << "Correct:" << std::endl;
  12778. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  12779. std::cerr << std::endl;
  12780. std::vector<const ggml_tensor *> done;
  12781. ggml_vk_print_graph_origin(tensor, done);
  12782. GGML_ABORT("fatal error");
  12783. } else {
  12784. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  12785. }
  12786. free(comp_result);
  12787. comp_result = nullptr;
  12788. comp_size = 0;
  12789. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12790. free(tensor_data);
  12791. }
  12792. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  12793. }
  12794. #endif
  12795. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)