ggml-vulkan.cpp 294 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414
  1. #include "ggml-vulkan.h"
  2. #ifdef GGML_VULKAN_RUN_TESTS
  3. #include <chrono>
  4. #endif
  5. #include <vulkan/vulkan.hpp>
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <iostream>
  9. #include <iomanip>
  10. #include <limits>
  11. #include <tuple>
  12. #include <vector>
  13. #include <sstream>
  14. #include <utility>
  15. #include <memory>
  16. #include "ggml.h"
  17. #include "ggml-backend-impl.h"
  18. #include "ggml-vulkan-shaders.hpp"
  19. #define VK_API_VERSION VK_API_VERSION_1_2
  20. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  21. #define VK_VENDOR_ID_AMD 0x1002
  22. #define VK_VENDOR_ID_APPLE 0x106b
  23. #define VK_VENDOR_ID_INTEL 0x8086
  24. #define VK_VENDOR_ID_NVIDIA 0x10de
  25. #define VK_DEVICE_DESCRIPTOR_POOL_MODE_UNKNOWN 0
  26. #define VK_DEVICE_DESCRIPTOR_POOL_MODE_MULTI 1
  27. #define VK_DEVICE_DESCRIPTOR_POOL_MODE_SINGLE 2
  28. #define VK_NUM_TYPES 16
  29. #define GGML_VK_MAX_NODES 8192
  30. #define MAX_VK_BUFFERS 256
  31. #ifndef K_QUANTS_PER_ITERATION
  32. #define K_QUANTS_PER_ITERATION 1
  33. #else
  34. static_assert(K_QUANTS_PER_ITERATION == 1 || K_QUANTS_PER_ITERATION == 2, "K_QUANTS_PER_ITERATION must be 1 or 2");
  35. #endif
  36. #define VK_CHECK(err, msg) \
  37. do { \
  38. vk::Result err_ = (err); \
  39. if (err_ != vk::Result::eSuccess) { \
  40. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  41. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  42. exit(1); \
  43. } \
  44. } while (0)
  45. struct ggml_backend_vk_context;
  46. struct vk_queue {
  47. uint32_t queue_family_index;
  48. vk::Queue queue;
  49. vk::CommandPool pool;
  50. uint32_t cmd_buffer_idx;
  51. std::vector<vk::CommandBuffer> cmd_buffers;
  52. vk::PipelineStageFlags stage_flags;
  53. };
  54. struct vk_pipeline_struct {
  55. std::string name;
  56. vk::ShaderModule shader_module;
  57. vk::DescriptorSetLayout dsl;
  58. std::vector<vk::DescriptorPool> descriptor_pools;
  59. std::vector<vk::DescriptorSet> descriptor_sets;
  60. uint32_t descriptor_set_idx;
  61. vk::PipelineLayout layout;
  62. vk::Pipeline pipeline;
  63. uint32_t push_constant_size;
  64. uint32_t parameter_count;
  65. std::array<uint32_t, 3> wg_denoms;
  66. uint32_t align;
  67. };
  68. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  69. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  70. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  71. struct vk_matmul_pipeline_struct {
  72. vk_pipeline l, m, s;
  73. vk_pipeline a_l, a_m, a_s;
  74. };
  75. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  76. struct vk_device {
  77. vk::PhysicalDevice physical_device;
  78. vk::PhysicalDeviceProperties properties;
  79. std::string name;
  80. uint64_t max_memory_allocation_size;
  81. bool fp16;
  82. vk::Device device;
  83. uint32_t vendor_id;
  84. vk_queue compute_queue;
  85. vk_queue transfer_queue;
  86. bool single_queue;
  87. uint32_t descriptor_set_mode;
  88. uint32_t subgroup_size;
  89. bool uma;
  90. bool initialized;
  91. size_t idx;
  92. vk_matmul_pipeline pipeline_matmul_f32;
  93. vk_matmul_pipeline pipeline_matmul_f16;
  94. vk_matmul_pipeline pipeline_matmul_f16_f32;
  95. vk_pipeline pipeline_matmul_split_k_reduce;
  96. vk_matmul_pipeline pipeline_dequant_mul_mat_mat[VK_NUM_TYPES];
  97. vk_pipeline pipeline_dequant[VK_NUM_TYPES];
  98. vk_pipeline pipeline_dequant_mul_mat_vec_f32[VK_NUM_TYPES];
  99. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32;
  100. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  101. vk_pipeline pipeline_get_rows[VK_NUM_TYPES];
  102. vk_pipeline pipeline_get_rows_f32[VK_NUM_TYPES];
  103. vk_pipeline pipeline_mul_f32;
  104. vk_pipeline pipeline_add_f32;
  105. vk_pipeline pipeline_scale_f32;
  106. vk_pipeline pipeline_sqr_f32;
  107. vk_pipeline pipeline_clamp_f32;
  108. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16;
  109. vk_pipeline pipeline_norm_f32;
  110. vk_pipeline pipeline_rms_norm_f32;
  111. vk_pipeline pipeline_gelu_f32;
  112. vk_pipeline pipeline_silu_f32;
  113. vk_pipeline pipeline_relu_f32;
  114. vk_pipeline pipeline_diag_mask_inf_f32;
  115. vk_pipeline pipeline_soft_max_f32;
  116. vk_pipeline pipeline_rope_f32, pipeline_rope_f16;
  117. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  118. vk_pipeline pipeline_argsort_f32;
  119. std::vector<vk_pipeline_ref> pipelines;
  120. ~vk_device() {
  121. #ifdef GGML_VULKAN_DEBUG
  122. std::cerr << "destroy device " << name << std::endl;
  123. #endif
  124. device.destroyCommandPool(compute_queue.pool);
  125. if (!single_queue) {
  126. device.destroyCommandPool(transfer_queue.pool);
  127. }
  128. for (auto& pipeline : pipelines) {
  129. if (pipeline.expired()) {
  130. continue;
  131. }
  132. vk_pipeline pl = pipeline.lock();
  133. ggml_vk_destroy_pipeline(device, pl);
  134. }
  135. pipelines.clear();
  136. device.destroy();
  137. }
  138. };
  139. struct vk_buffer_struct {
  140. vk::Buffer buffer;
  141. vk::DeviceMemory device_memory;
  142. vk::MemoryPropertyFlags memory_property_flags;
  143. void * ptr;
  144. size_t size = 0;
  145. ggml_backend_vk_context * ctx;
  146. std::shared_ptr<vk_device> device;
  147. ~vk_buffer_struct() {
  148. if (size == 0) {
  149. return;
  150. }
  151. #ifdef GGML_VULKAN_DEBUG
  152. std::cerr << "~vk_buffer_struct(" << buffer << ", " << size << ")" << std::endl;
  153. #endif
  154. device->device.freeMemory(device_memory);
  155. device->device.destroyBuffer(buffer);
  156. }
  157. };
  158. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  159. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  160. struct vk_subbuffer {
  161. vk_buffer buffer;
  162. uint64_t offset;
  163. uint64_t size;
  164. };
  165. struct vk_semaphore {
  166. vk::Semaphore s;
  167. uint64_t value;
  168. };
  169. struct vk_submission {
  170. vk::CommandBuffer buffer;
  171. std::vector<vk_semaphore> wait_semaphores;
  172. std::vector<vk_semaphore> signal_semaphores;
  173. };
  174. typedef std::vector<vk_submission> vk_sequence;
  175. struct vk_op_push_constants {
  176. uint32_t KX;
  177. uint32_t KY;
  178. float param1;
  179. float param2;
  180. };
  181. struct vk_op_unary_push_constants {
  182. uint32_t ne;
  183. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  184. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  185. uint32_t d_offset;
  186. float param1; float param2;
  187. };
  188. struct vk_op_binary_push_constants {
  189. uint32_t ne;
  190. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  191. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  192. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  193. uint32_t d_offset;
  194. float param1; float param2;
  195. };
  196. struct vk_op_diag_mask_push_constants {
  197. uint32_t ncols;
  198. uint32_t rows_per_channel;
  199. int32_t n_past;
  200. };
  201. struct vk_op_rope_push_constants {
  202. uint32_t ncols;
  203. float freq_scale;
  204. uint32_t p_delta_rows;
  205. float freq_base;
  206. float ext_factor;
  207. float attn_factor;
  208. float corr_dims[4];
  209. };
  210. struct vk_op_rope_neox_push_constants {
  211. uint32_t ncols;
  212. uint32_t ndims;
  213. float freq_scale;
  214. uint32_t p_delta_rows;
  215. float freq_base;
  216. float ext_factor;
  217. float attn_factor;
  218. float corr_dims[4];
  219. float theta_scale;
  220. float inv_ndims;
  221. };
  222. struct vk_op_soft_max_push_constants {
  223. uint32_t KX;
  224. uint32_t KY;
  225. uint32_t KZ;
  226. float scale;
  227. float max_bias;
  228. float m0;
  229. float m1;
  230. uint32_t n_head_log2;
  231. };
  232. struct vk_op_argsort_push_constants {
  233. uint32_t ncols;
  234. bool ascending;
  235. };
  236. // Allow pre-recording command buffers
  237. struct vk_staging_memcpy {
  238. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  239. void * dst;
  240. const void * src;
  241. size_t n;
  242. };
  243. struct vk_context {
  244. size_t idx;
  245. vk_submission * s;
  246. std::vector<vk_sequence> seqs;
  247. ggml_tensor * exit_tensor;
  248. std::vector<vk_staging_memcpy> in_memcpys;
  249. std::vector<vk_staging_memcpy> out_memcpys;
  250. vk_queue * q;
  251. };
  252. struct ggml_tensor_extra_gpu {
  253. bool ready;
  254. size_t ctx_idx;
  255. vk_buffer_ref buffer_gpu;
  256. uint64_t offset;
  257. void reset() {
  258. ready = false;
  259. ctx_idx = 0;
  260. buffer_gpu.reset();
  261. offset = 0;
  262. }
  263. };
  264. struct ggml_vk_garbage_collector {
  265. std::vector<vk_semaphore> tl_semaphores;
  266. std::vector<vk_semaphore> semaphores;
  267. std::vector<vk::Event> events;
  268. std::vector<vk_buffer> temp_buffers;
  269. std::vector<vk_context> contexts;
  270. };
  271. struct ggml_backend_vk_context {
  272. std::string name;
  273. std::shared_ptr<vk_device> device;
  274. size_t semaphore_idx, event_idx;
  275. ggml_vk_garbage_collector gc;
  276. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  277. size_t prealloc_size_qx, prealloc_size_qy, prealloc_size_x, prealloc_size_y, prealloc_size_split_k;
  278. vk_buffer prealloc_qx, prealloc_qy, prealloc_x, prealloc_y, prealloc_split_k;
  279. vk::Fence fence;
  280. vk_buffer staging;
  281. size_t staging_size;
  282. size_t staging_offset;
  283. vk_buffer sync_staging;
  284. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  285. vk_context * compute_ctx;
  286. vk_context * transfer_ctx;
  287. bool disable;
  288. bool initialized;
  289. size_t idx;
  290. };
  291. struct vk_instance {
  292. vk::Instance instance;
  293. std::vector<size_t> device_indices;
  294. ggml_backend_t backends[GGML_VK_MAX_DEVICES];
  295. ggml_backend_vk_context contexts[GGML_VK_MAX_DEVICES];
  296. ggml_backend_buffer_type buffer_types[GGML_VK_MAX_DEVICES];
  297. bool initialized[GGML_VK_MAX_DEVICES];
  298. };
  299. static std::shared_ptr<vk_device> ggml_vk_get_device(size_t idx) {
  300. #ifdef GGML_VULKAN_DEBUG
  301. std::cerr << "ggml_vk_get_device(" << idx << ")" << std::endl;
  302. #endif
  303. static std::weak_ptr<vk_device> devices[GGML_VK_MAX_DEVICES];
  304. if (devices[idx].expired()) {
  305. #ifdef GGML_VULKAN_DEBUG
  306. std::cerr << "Initializing new vk_device" << std::endl;
  307. #endif
  308. std::shared_ptr<vk_device> device = std::make_shared<vk_device>();
  309. device->initialized = false;
  310. devices[idx] = device;
  311. return device;
  312. }
  313. return devices[idx].lock();
  314. }
  315. #ifdef GGML_VULKAN_CHECK_RESULTS
  316. static size_t vk_skip_checks;
  317. static size_t vk_output_tensor;
  318. static void ggml_vk_print_tensor(ggml_backend * ctx, const ggml_tensor * tensor, const char * name);
  319. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor);
  320. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor);
  321. #endif
  322. 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);
  323. static bool vk_instance_initialized = false;
  324. static vk_instance vk_instance;
  325. GGML_CALL static void ggml_backend_vk_free(ggml_backend_t backend);
  326. static void ggml_vk_create_pipeline(ggml_backend_vk_context * ctx, vk_pipeline& pipeline, const std::string& name, size_t spv_size, const void* spv_data, const std::string& entrypoint, uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t>&& specialization_constants, uint32_t align) {
  327. #ifdef GGML_VULKAN_DEBUG
  328. std::cerr << "ggml_vk_create_pipeline(" << name << ", " << entrypoint << ", " << parameter_count << ", " << push_constant_size << ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " << align << ")" << std::endl;
  329. #endif
  330. GGML_ASSERT(parameter_count > 0);
  331. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  332. pipeline = std::make_shared<vk_pipeline_struct>();
  333. pipeline->name = name;
  334. pipeline->parameter_count = parameter_count;
  335. pipeline->push_constant_size = push_constant_size;
  336. pipeline->wg_denoms = wg_denoms;
  337. pipeline->align = align;
  338. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  339. pipeline->shader_module = ctx->device->device.createShaderModule(shader_module_create_info);
  340. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  341. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  342. for (uint32_t i = 0; i < parameter_count; i++) {
  343. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  344. dsl_binding_flags.push_back({});
  345. }
  346. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  347. vk::PushConstantRange pcr(
  348. vk::ShaderStageFlagBits::eCompute,
  349. 0,
  350. pipeline->push_constant_size
  351. );
  352. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  353. {},
  354. dsl_binding);
  355. descriptor_set_layout_create_info.setPNext(&dslbfci);
  356. pipeline->dsl = ctx->device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  357. // Check if device supports multiple descriptors per pool
  358. if (ctx->device->descriptor_set_mode == VK_DEVICE_DESCRIPTOR_POOL_MODE_UNKNOWN) {
  359. const uint32_t alloc_count = 2;
  360. // Try allocating multiple sets from one pool
  361. // This fails on AMD for some reason, so add a fall back to allocating one pool per set
  362. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count);
  363. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, alloc_count, descriptor_pool_size);
  364. vk::DescriptorPool pool = ctx->device->device.createDescriptorPool(descriptor_pool_create_info);
  365. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  366. for (uint32_t i = 0; i < alloc_count; i++) {
  367. layouts[i] = pipeline->dsl;
  368. }
  369. try {
  370. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pool, alloc_count, layouts.data());
  371. std::vector<vk::DescriptorSet> sets = ctx->device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  372. } catch(vk::OutOfPoolMemoryError const&) {
  373. ctx->device->descriptor_set_mode = VK_DEVICE_DESCRIPTOR_POOL_MODE_SINGLE;
  374. }
  375. ctx->device->device.destroyDescriptorPool(pool);
  376. }
  377. if (ctx->device->descriptor_set_mode == VK_DEVICE_DESCRIPTOR_POOL_MODE_MULTI) {
  378. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count);
  379. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, 128, descriptor_pool_size);
  380. pipeline->descriptor_pools.push_back(ctx->device->device.createDescriptorPool(descriptor_pool_create_info));
  381. }
  382. pipeline->descriptor_set_idx = 0;
  383. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), pipeline->dsl, pcr);
  384. pipeline->layout = ctx->device->device.createPipelineLayout(pipeline_layout_create_info);
  385. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  386. for (size_t i = 0; i < specialization_constants.size(); i++) {
  387. specialization_entries[i].constantID = i;
  388. specialization_entries[i].offset = i * sizeof(uint32_t);
  389. specialization_entries[i].size = sizeof(uint32_t);
  390. }
  391. vk::SpecializationInfo specialization_info(
  392. specialization_entries.size(),
  393. specialization_entries.data(),
  394. specialization_constants.size() * sizeof(uint32_t),
  395. specialization_constants.data()
  396. );
  397. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  398. vk::PipelineShaderStageCreateFlags(),
  399. vk::ShaderStageFlagBits::eCompute,
  400. pipeline->shader_module,
  401. entrypoint.c_str(),
  402. &specialization_info);
  403. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  404. vk::PipelineCreateFlags(),
  405. pipeline_shader_create_info,
  406. pipeline->layout);
  407. pipeline->pipeline = ctx->device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  408. ctx->device->pipelines.push_back(pipeline);
  409. }
  410. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  411. #ifdef GGML_VULKAN_DEBUG
  412. std::cerr << "ggml_pipeline_destroy_pipeline(" << pipeline->name << ")" << std::endl;
  413. #endif
  414. for (auto& pool : pipeline->descriptor_pools) {
  415. device.destroyDescriptorPool(pool);
  416. }
  417. pipeline->descriptor_pools.clear();
  418. pipeline->descriptor_sets.clear();
  419. pipeline->descriptor_set_idx = 0;
  420. device.destroyDescriptorSetLayout(pipeline->dsl);
  421. device.destroyPipelineLayout(pipeline->layout);
  422. device.destroyShaderModule(pipeline->shader_module);
  423. device.destroyPipeline(pipeline->pipeline);
  424. }
  425. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx, vk_pipeline& pipeline, uint32_t n) {
  426. #ifdef GGML_VULKAN_DEBUG
  427. std::cerr << "ggml_pipeline_allocate_descriptor_sets(" << pipeline->name << ", " << n << ")" << std::endl;
  428. #endif
  429. if (pipeline->descriptor_sets.size() >= pipeline->descriptor_set_idx + n) {
  430. // Enough descriptors are available
  431. return;
  432. }
  433. if (ctx->device->descriptor_set_mode == VK_DEVICE_DESCRIPTOR_POOL_MODE_MULTI) {
  434. const uint32_t alloc_count = pipeline->descriptor_set_idx + n - pipeline->descriptor_sets.size();
  435. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  436. for (uint32_t i = 0; i < alloc_count; i++) {
  437. layouts[i] = pipeline->dsl;
  438. }
  439. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pipeline->descriptor_pools[0], alloc_count, layouts.data());
  440. std::vector<vk::DescriptorSet> sets = ctx->device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  441. pipeline->descriptor_sets.insert(pipeline->descriptor_sets.end(), sets.begin(), sets.end());
  442. } else {
  443. for (uint32_t i = pipeline->descriptor_sets.size(); i < pipeline->descriptor_set_idx + n; i++) {
  444. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count);
  445. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, 1, descriptor_pool_size);
  446. pipeline->descriptor_pools.push_back(ctx->device->device.createDescriptorPool(descriptor_pool_create_info));
  447. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pipeline->descriptor_pools[i], 1, &pipeline->dsl);
  448. std::vector<vk::DescriptorSet> sets = ctx->device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  449. pipeline->descriptor_sets.push_back(sets[0]);
  450. }
  451. }
  452. }
  453. static void ggml_pipeline_cleanup(vk_pipeline& pipeline) {
  454. #ifdef GGML_VULKAN_DEBUG
  455. std::cerr << "ggml_pipeline_cleanup(" << pipeline->name << ")" << std::endl;
  456. #endif
  457. pipeline->descriptor_set_idx = 0;
  458. }
  459. static vk::CommandBuffer ggml_vk_create_cmd_buffer(ggml_backend_vk_context * ctx, vk_queue& q) {
  460. #ifdef GGML_VULKAN_DEBUG
  461. std::cerr << "ggml_vk_create_cmd_buffer()" << std::endl;
  462. #endif
  463. if (q.cmd_buffers.size() > q.cmd_buffer_idx) {
  464. // Reuse command buffer
  465. return q.cmd_buffers[q.cmd_buffer_idx++];
  466. }
  467. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  468. q.pool,
  469. vk::CommandBufferLevel::ePrimary,
  470. 1);
  471. const std::vector<vk::CommandBuffer> cmd_buffers = ctx->device->device.allocateCommandBuffers(command_buffer_alloc_info);
  472. auto buf = cmd_buffers.front();
  473. q.cmd_buffers.push_back(buf);
  474. q.cmd_buffer_idx++;
  475. return buf;
  476. }
  477. static vk_submission ggml_vk_create_submission(ggml_backend_vk_context * ctx, vk_queue& q, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  478. #ifdef GGML_VULKAN_DEBUG
  479. std::cerr << "ggml_vk_create_submission()" << std::endl;
  480. #endif
  481. vk_submission s;
  482. s.buffer = ggml_vk_create_cmd_buffer(ctx, q);
  483. s.wait_semaphores = std::move(wait_semaphores);
  484. s.signal_semaphores = std::move(signal_semaphores);
  485. return s;
  486. }
  487. static void ggml_vk_submit(vk_context * ctx, vk::Fence fence) {
  488. #ifdef GGML_VULKAN_DEBUG
  489. std::cerr << "ggml_vk_submit(" << ctx->seqs.size() << ", " << fence << ")" << std::endl;
  490. #endif
  491. if (ctx->seqs.empty()) {
  492. return;
  493. }
  494. std::vector<std::vector<uint64_t>> tl_wait_vals;
  495. std::vector<std::vector<uint64_t>> tl_signal_vals;
  496. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  497. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  498. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  499. std::vector<vk::SubmitInfo> submit_infos;
  500. int idx = -1;
  501. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  502. size_t reserve = 0;
  503. for (const auto& sequence : ctx->seqs) {
  504. reserve += sequence.size();
  505. }
  506. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  507. tl_wait_semaphores.reserve(reserve);
  508. tl_wait_vals.reserve(reserve);
  509. tl_signal_semaphores.reserve(reserve);
  510. tl_signal_vals.reserve(reserve);
  511. tl_submit_infos.reserve(reserve);
  512. submit_infos.reserve(reserve);
  513. stage_flags.reserve(reserve);
  514. for (const auto& sequence : ctx->seqs) {
  515. for (const auto& submission : sequence) {
  516. stage_flags.push_back({});
  517. idx++;
  518. tl_wait_vals.push_back({});
  519. tl_wait_semaphores.push_back({});
  520. tl_signal_vals.push_back({});
  521. tl_signal_semaphores.push_back({});
  522. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  523. stage_flags[idx].push_back(ctx->q->stage_flags);
  524. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  525. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  526. }
  527. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  528. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  529. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  530. }
  531. tl_submit_infos.push_back({
  532. (uint32_t) submission.wait_semaphores.size(),
  533. tl_wait_vals[idx].data(),
  534. (uint32_t) submission.signal_semaphores.size(),
  535. tl_signal_vals[idx].data(),
  536. });
  537. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  538. tl_submit_infos[idx].pNext = nullptr;
  539. vk::SubmitInfo si{
  540. (uint32_t) submission.wait_semaphores.size(),
  541. tl_wait_semaphores[idx].data(),
  542. stage_flags[idx].data(),
  543. 1,
  544. &submission.buffer,
  545. (uint32_t) submission.signal_semaphores.size(),
  546. tl_signal_semaphores[idx].data(),
  547. };
  548. si.setPNext(&tl_submit_infos[idx]);
  549. submit_infos.push_back(si);
  550. }
  551. }
  552. ctx->q->queue.submit(submit_infos, fence);
  553. ctx->seqs.clear();
  554. }
  555. 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) {
  556. #ifdef GGML_VULKAN_DEBUG
  557. std::cerr << "ggml_vk_find_queue_family_index()" << std::endl;
  558. #endif
  559. const uint32_t qfsize = queue_family_props.size();
  560. // Try with avoid preferences first
  561. for (uint32_t i = 0; i < qfsize; i++) {
  562. 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)) {
  563. return i;
  564. }
  565. }
  566. // Fall back to only required
  567. for (size_t i = 0; i < qfsize; i++) {
  568. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  569. return i;
  570. }
  571. }
  572. // Fall back to reusing compute queue
  573. for (size_t i = 0; i < qfsize; i++) {
  574. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  575. return i;
  576. }
  577. }
  578. // Fall back to ignoring min_num_queries
  579. for (size_t i = 0; i < qfsize; i++) {
  580. if (queue_family_props[i].queueFlags & required) {
  581. return i;
  582. }
  583. }
  584. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  585. for(auto &q_family : queue_family_props) {
  586. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  587. }
  588. abort();
  589. }
  590. static void ggml_vk_create_queue(ggml_backend_vk_context * ctx, vk_queue& q, uint32_t queue_family_index, uint32_t queue_index, vk::PipelineStageFlags&& stage_flags) {
  591. #ifdef GGML_VULKAN_DEBUG
  592. std::cerr << "ggml_vk_create_queue()" << std::endl;
  593. #endif
  594. q.queue_family_index = queue_family_index;
  595. vk::CommandPoolCreateInfo command_pool_create_info_compute(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), queue_family_index);
  596. q.pool = ctx->device->device.createCommandPool(command_pool_create_info_compute);
  597. q.cmd_buffer_idx = 0;
  598. q.queue = ctx->device->device.getQueue(queue_family_index, queue_index);
  599. q.stage_flags = stage_flags;
  600. }
  601. static vk_context * ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_queue& q) {
  602. #ifdef GGML_VULKAN_DEBUG
  603. std::cerr << "ggml_vk_create_context()" << std::endl;
  604. #endif
  605. ctx->gc.contexts.emplace_back();
  606. vk_context * result = &ctx->gc.contexts[ctx->gc.contexts.size() - 1];
  607. memset((void *) result, 0, sizeof(vk_context));
  608. result->idx = ctx->gc.contexts.size() - 1;
  609. result->q = &q;
  610. return result;
  611. }
  612. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  613. #ifdef GGML_VULKAN_DEBUG
  614. std::cerr << "ggml_vk_create_timeline_semaphore()" << std::endl;
  615. #endif
  616. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  617. vk::SemaphoreCreateInfo ci{};
  618. ci.setPNext(&tci);
  619. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  620. ctx->gc.semaphores.push_back({ semaphore, 0 });
  621. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  622. }
  623. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  624. #ifdef GGML_VULKAN_DEBUG
  625. std::cerr << "ggml_vk_create_timeline_semaphore()" << std::endl;
  626. #endif
  627. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  628. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  629. vk::SemaphoreCreateInfo ci{};
  630. ci.setPNext(&tci);
  631. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  632. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  633. }
  634. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  635. }
  636. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  637. if (ctx->event_idx >= ctx->gc.events.size()) {
  638. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  639. }
  640. return ctx->gc.events[ctx->event_idx++];
  641. }
  642. static void ggml_vk_queue_cleanup(ggml_backend_vk_context * ctx, vk_queue& q) {
  643. #ifdef GGML_VULKAN_DEBUG
  644. std::cerr << "ggml_vk_queue_cleanup()" << std::endl;
  645. #endif
  646. // Requires command buffers to be done
  647. ctx->device->device.resetCommandPool(q.pool);
  648. q.cmd_buffer_idx = 0;
  649. }
  650. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  651. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  652. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  653. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  654. (flags & memory_type.propertyFlags) == flags &&
  655. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  656. return static_cast<int32_t>(i);
  657. }
  658. }
  659. return UINT32_MAX;
  660. }
  661. static vk_buffer ggml_vk_create_buffer(ggml_backend_vk_context * ctx, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  662. #ifdef GGML_VULKAN_DEBUG
  663. std::cerr << "ggml_vk_create_buffer(" << size << ", " << to_string(req_flags) << ", " << to_string(fallback_flags) << ")" << std::endl;
  664. #endif
  665. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  666. if (size == 0) {
  667. buf->size = 0;
  668. return buf;
  669. }
  670. buf->size = size;
  671. vk::BufferCreateInfo buffer_create_info{
  672. vk::BufferCreateFlags(),
  673. size,
  674. vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst,
  675. vk::SharingMode::eExclusive,
  676. 0,
  677. nullptr,
  678. };
  679. buf->buffer = ctx->device->device.createBuffer(buffer_create_info);
  680. vk::MemoryRequirements mem_req = ctx->device->device.getBufferMemoryRequirements(buf->buffer);
  681. vk::PhysicalDeviceMemoryProperties mem_props = ctx->device->physical_device.getMemoryProperties();
  682. uint32_t memory_type_index = UINT32_MAX;
  683. memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  684. buf->memory_property_flags = req_flags;
  685. if (memory_type_index == UINT32_MAX && fallback_flags) {
  686. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  687. buf->memory_property_flags = fallback_flags;
  688. }
  689. if (memory_type_index == UINT32_MAX) {
  690. ctx->device->device.destroyBuffer(buf->buffer);
  691. buf->size = 0;
  692. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  693. }
  694. try {
  695. buf->device_memory = ctx->device->device.allocateMemory({ mem_req.size, memory_type_index });
  696. } catch (const vk::SystemError& e) {
  697. // Out of Host/Device memory, clean up buffer
  698. ctx->device->device.destroyBuffer(buf->buffer);
  699. buf->size = 0;
  700. throw e;
  701. }
  702. buf->ptr = nullptr;
  703. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  704. buf->ptr = ctx->device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  705. }
  706. ctx->device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  707. buf->ctx = ctx;
  708. buf->device = ctx->device;
  709. #ifdef GGML_VULKAN_DEBUG
  710. std::cerr << "Created buffer " << buf->buffer << std::endl;
  711. #endif
  712. return buf;
  713. }
  714. static vk_buffer ggml_vk_create_buffer_check(ggml_backend_vk_context * ctx, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  715. try {
  716. return ggml_vk_create_buffer(ctx, size, req_flags, fallback_flags);
  717. } catch (const vk::SystemError& e) {
  718. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  719. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  720. throw e;
  721. }
  722. }
  723. static vk_buffer ggml_vk_create_buffer_device(ggml_backend_vk_context * ctx, size_t size) {
  724. vk_buffer buf;
  725. try {
  726. if (ctx->device->uma) {
  727. // Fall back to host memory type
  728. buf = ggml_vk_create_buffer(ctx, size, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  729. } else {
  730. buf = ggml_vk_create_buffer(ctx, size, vk::MemoryPropertyFlagBits::eDeviceLocal);
  731. }
  732. } catch (const vk::SystemError& e) {
  733. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  734. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  735. throw e;
  736. }
  737. return buf;
  738. }
  739. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  740. buf.reset();
  741. }
  742. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  743. return { buf, 0, VK_WHOLE_SIZE };
  744. }
  745. static void ggml_vk_sync_buffers(vk_context * ctx) {
  746. #ifdef GGML_VULKAN_DEBUG
  747. std::cerr << "ggml_vk_sync_buffers()" << std::endl;
  748. #endif
  749. const std::vector<vk::MemoryBarrier> mem_barriers{ { { vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite }, { vk::AccessFlagBits::eMemoryRead | vk::AccessFlagBits::eMemoryWrite } } };
  750. ctx->s->buffer.pipelineBarrier(
  751. ctx->q->stage_flags,
  752. ctx->q->stage_flags,
  753. {},
  754. mem_barriers,
  755. {},
  756. {}
  757. );
  758. }
  759. static void ggml_vk_wait_events(vk_context * ctx, std::vector<vk::Event>&& events) {
  760. #ifdef GGML_VULKAN_DEBUG
  761. std::cerr << "ggml_vk_wait_events()" << std::endl;
  762. #endif
  763. if (events.empty()) {
  764. return;
  765. }
  766. ctx->s->buffer.waitEvents(
  767. events,
  768. ctx->q->stage_flags,
  769. ctx->q->stage_flags,
  770. {},
  771. {},
  772. {}
  773. );
  774. }
  775. static bool ggml_vk_build_shader(ggml_type type) {
  776. switch(type) {
  777. case GGML_TYPE_F16:
  778. case GGML_TYPE_Q4_0:
  779. case GGML_TYPE_Q4_1:
  780. case GGML_TYPE_Q5_0:
  781. case GGML_TYPE_Q5_1:
  782. case GGML_TYPE_Q8_0:
  783. case GGML_TYPE_Q2_K:
  784. case GGML_TYPE_Q3_K:
  785. case GGML_TYPE_Q4_K:
  786. case GGML_TYPE_Q5_K:
  787. case GGML_TYPE_Q6_K:
  788. return true;
  789. default:
  790. return false;
  791. }
  792. }
  793. static void ggml_vk_load_shaders(ggml_backend_vk_context * ctx) {
  794. #ifdef GGML_VULKAN_DEBUG
  795. std::cerr << "ggml_vk_load_shaders(" << ctx->name << ")" << std::endl;
  796. #endif
  797. const std::shared_ptr<vk_device> device = ctx->device;
  798. // mulmat
  799. std::initializer_list<uint32_t> warptile_l = { 128, 128, 128, 16, device->subgroup_size * 2, 64, 2, 4, 4, device->subgroup_size };
  800. std::initializer_list<uint32_t> warptile_m = { 128, 64, 64, 16, device->subgroup_size, 32, 2, 4, 2, device->subgroup_size };
  801. std::initializer_list<uint32_t> warptile_s = { device->subgroup_size, 32, 32, 16, 32, 32, 2, 2, 2, device->subgroup_size };
  802. std::initializer_list<uint32_t> warptile_mmq_l = { 128, 128, 128, 32, device->subgroup_size * 2, 64, 2, 4, 4, device->subgroup_size };
  803. std::initializer_list<uint32_t> warptile_mmq_m = { 128, 64, 64, 32, device->subgroup_size, 32, 2, 4, 2, device->subgroup_size };
  804. std::initializer_list<uint32_t> warptile_mmq_s = { device->subgroup_size, 32, 32, 32, 32, 32, 2, 2, 2, device->subgroup_size };
  805. std::array<uint32_t, 3> l_wg_denoms = {128, 128, 1 };
  806. std::array<uint32_t, 3> m_wg_denoms = { 64, 64, 1 };
  807. std::array<uint32_t, 3> s_wg_denoms = { 32, 32, 1 };
  808. uint32_t l_align = 128;
  809. uint32_t m_align = 64;
  810. uint32_t s_align = 32;
  811. ctx->device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  812. ctx->device->pipeline_matmul_f16_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  813. ctx->device->pipeline_matmul_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  814. ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0] = std::make_shared<vk_matmul_pipeline_struct>();
  815. ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1] = std::make_shared<vk_matmul_pipeline_struct>();
  816. ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0] = std::make_shared<vk_matmul_pipeline_struct>();
  817. ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1] = std::make_shared<vk_matmul_pipeline_struct>();
  818. ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0] = std::make_shared<vk_matmul_pipeline_struct>();
  819. if (device->fp16) {
  820. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->l, "matmul_f32_l", matmul_f32_len, matmul_f32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  821. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->m, "matmul_f32_m", matmul_f32_len, matmul_f32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  822. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->s, "matmul_f32_s", matmul_f32_len, matmul_f32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  823. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->a_l, "matmul_f32_aligned_l", matmul_f32_aligned_len, matmul_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  824. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->a_m, "matmul_f32_aligned_m", matmul_f32_aligned_len, matmul_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  825. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->a_s, "matmul_f32_aligned_s", matmul_f32_aligned_len, matmul_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  826. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->l, "matmul_f16_l", matmul_f16_len, matmul_f16_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  827. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->m, "matmul_f16_m", matmul_f16_len, matmul_f16_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  828. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->s, "matmul_f16_s", matmul_f16_len, matmul_f16_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  829. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->a_l, "matmul_f16_aligned_l", matmul_f16_aligned_len, matmul_f16_aligned_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  830. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->a_m, "matmul_f16_aligned_m", matmul_f16_aligned_len, matmul_f16_aligned_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  831. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->a_s, "matmul_f16_aligned_s", matmul_f16_aligned_len, matmul_f16_aligned_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  832. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->l, "matmul_f16_f32_l", matmul_f16_f32_len, matmul_f16_f32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  833. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->m, "matmul_f16_f32_m", matmul_f16_f32_len, matmul_f16_f32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  834. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->s, "matmul_f16_f32_s", matmul_f16_f32_len, matmul_f16_f32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  835. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->a_l, "matmul_f16_f32_aligned_l", matmul_f16_f32_aligned_len, matmul_f16_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  836. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->a_m, "matmul_f16_f32_aligned_m", matmul_f16_f32_aligned_len, matmul_f16_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  837. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->a_s, "matmul_f16_f32_aligned_s", matmul_f16_f32_aligned_len, matmul_f16_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  838. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->l, "matmul_q4_0_f32_l", matmul_q4_0_f32_len, matmul_q4_0_f32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  839. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->m, "matmul_q4_0_f32_m", matmul_q4_0_f32_len, matmul_q4_0_f32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  840. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->s, "matmul_q4_0_f32_s", matmul_q4_0_f32_len, matmul_q4_0_f32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  841. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->a_l, "matmul_q4_0_f32_aligned_l", matmul_q4_0_f32_aligned_len, matmul_q4_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  842. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->a_m, "matmul_q4_0_f32_aligned_m", matmul_q4_0_f32_aligned_len, matmul_q4_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  843. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->a_s, "matmul_q4_0_f32_aligned_s", matmul_q4_0_f32_aligned_len, matmul_q4_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  844. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->l, "matmul_q4_0_f32_l", matmul_q4_1_f32_len, matmul_q4_1_f32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  845. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->m, "matmul_q4_0_f32_m", matmul_q4_1_f32_len, matmul_q4_1_f32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  846. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->s, "matmul_q4_0_f32_s", matmul_q4_1_f32_len, matmul_q4_1_f32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  847. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->a_l, "matmul_q4_0_f32_aligned_l", matmul_q4_1_f32_aligned_len, matmul_q4_1_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  848. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->a_m, "matmul_q4_0_f32_aligned_m", matmul_q4_1_f32_aligned_len, matmul_q4_1_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  849. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->a_s, "matmul_q4_0_f32_aligned_s", matmul_q4_1_f32_aligned_len, matmul_q4_1_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  850. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->l, "matmul_q5_0_f32_l", matmul_q5_0_f32_len, matmul_q5_0_f32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  851. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->m, "matmul_q5_0_f32_m", matmul_q5_0_f32_len, matmul_q5_0_f32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  852. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->s, "matmul_q5_0_f32_s", matmul_q5_0_f32_len, matmul_q5_0_f32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  853. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->a_l, "matmul_q5_0_f32_aligned_l", matmul_q5_0_f32_aligned_len, matmul_q5_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  854. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->a_m, "matmul_q5_0_f32_aligned_m", matmul_q5_0_f32_aligned_len, matmul_q5_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  855. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->a_s, "matmul_q5_0_f32_aligned_s", matmul_q5_0_f32_aligned_len, matmul_q5_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  856. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->l, "matmul_q5_1_f32_l", matmul_q5_1_f32_len, matmul_q5_1_f32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  857. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->m, "matmul_q5_1_f32_m", matmul_q5_1_f32_len, matmul_q5_1_f32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  858. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->s, "matmul_q5_1_f32_s", matmul_q5_1_f32_len, matmul_q5_1_f32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  859. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->a_l, "matmul_q5_1_f32_aligned_l", matmul_q5_1_f32_aligned_len, matmul_q5_1_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  860. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->a_m, "matmul_q5_1_f32_aligned_m", matmul_q5_1_f32_aligned_len, matmul_q5_1_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  861. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->a_s, "matmul_q5_1_f32_aligned_s", matmul_q5_1_f32_aligned_len, matmul_q5_1_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  862. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->l, "matmul_q8_0_f32_l", matmul_q8_0_f32_len, matmul_q8_0_f32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  863. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->m, "matmul_q8_0_f32_m", matmul_q8_0_f32_len, matmul_q8_0_f32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  864. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->s, "matmul_q8_0_f32_s", matmul_q8_0_f32_len, matmul_q8_0_f32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  865. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->a_l, "matmul_q8_0_f32_aligned_l", matmul_q8_0_f32_aligned_len, matmul_q8_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  866. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->a_m, "matmul_q8_0_f32_aligned_m", matmul_q8_0_f32_aligned_len, matmul_q8_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  867. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->a_s, "matmul_q8_0_f32_aligned_s", matmul_q8_0_f32_aligned_len, matmul_q8_0_f32_aligned_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  868. } else {
  869. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->l, "matmul_f32_l", matmul_f32_fp32_len, matmul_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  870. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->m, "matmul_f32_m", matmul_f32_fp32_len, matmul_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  871. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->s, "matmul_f32_s", matmul_f32_fp32_len, matmul_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  872. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->a_l, "matmul_f32_aligned_l", matmul_f32_aligned_fp32_len, matmul_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  873. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->a_m, "matmul_f32_aligned_m", matmul_f32_aligned_fp32_len, matmul_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  874. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f32->a_s, "matmul_f32_aligned_s", matmul_f32_aligned_fp32_len, matmul_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  875. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->l, "matmul_f16_l", matmul_f16_fp32_len, matmul_f16_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  876. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->m, "matmul_f16_m", matmul_f16_fp32_len, matmul_f16_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  877. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->s, "matmul_f16_s", matmul_f16_fp32_len, matmul_f16_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  878. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->a_l, "matmul_f16_aligned_l", matmul_f16_aligned_fp32_len, matmul_f16_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  879. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->a_m, "matmul_f16_aligned_m", matmul_f16_aligned_fp32_len, matmul_f16_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  880. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16->a_s, "matmul_f16_aligned_s", matmul_f16_aligned_fp32_len, matmul_f16_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  881. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->l, "matmul_f16_f32_l", matmul_f16_f32_fp32_len, matmul_f16_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, 1);
  882. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->m, "matmul_f16_f32_m", matmul_f16_f32_fp32_len, matmul_f16_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, 1);
  883. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->s, "matmul_f16_f32_s", matmul_f16_f32_fp32_len, matmul_f16_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, 1);
  884. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->a_l, "matmul_f16_f32_aligned_l", matmul_f16_f32_aligned_fp32_len, matmul_f16_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_l, l_align);
  885. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->a_m, "matmul_f16_f32_aligned_m", matmul_f16_f32_aligned_fp32_len, matmul_f16_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_m, m_align);
  886. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_f16_f32->a_s, "matmul_f16_f32_aligned_s", matmul_f16_f32_aligned_fp32_len, matmul_f16_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_s, s_align);
  887. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->l, "matmul_q4_0_f32_l", matmul_q4_0_f32_fp32_len, matmul_q4_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  888. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->m, "matmul_q4_0_f32_m", matmul_q4_0_f32_fp32_len, matmul_q4_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  889. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->s, "matmul_q4_0_f32_s", matmul_q4_0_f32_fp32_len, matmul_q4_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  890. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->a_l, "matmul_q4_0_f32_aligned_l", matmul_q4_0_f32_aligned_fp32_len, matmul_q4_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  891. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->a_m, "matmul_q4_0_f32_aligned_m", matmul_q4_0_f32_aligned_fp32_len, matmul_q4_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  892. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0]->a_s, "matmul_q4_0_f32_aligned_s", matmul_q4_0_f32_aligned_fp32_len, matmul_q4_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  893. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->l, "matmul_q4_1_f32_l", matmul_q4_1_f32_fp32_len, matmul_q4_1_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  894. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->m, "matmul_q4_1_f32_m", matmul_q4_1_f32_fp32_len, matmul_q4_1_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  895. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->s, "matmul_q4_1_f32_s", matmul_q4_1_f32_fp32_len, matmul_q4_1_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  896. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->a_l, "matmul_q4_1_f32_aligned_l", matmul_q4_1_f32_aligned_fp32_len, matmul_q4_1_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  897. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->a_m, "matmul_q4_1_f32_aligned_m", matmul_q4_1_f32_aligned_fp32_len, matmul_q4_1_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  898. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1]->a_s, "matmul_q4_1_f32_aligned_s", matmul_q4_1_f32_aligned_fp32_len, matmul_q4_1_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  899. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->l, "matmul_q5_0_f32_l", matmul_q5_0_f32_fp32_len, matmul_q5_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  900. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->m, "matmul_q5_0_f32_m", matmul_q5_0_f32_fp32_len, matmul_q5_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  901. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->s, "matmul_q5_0_f32_s", matmul_q5_0_f32_fp32_len, matmul_q5_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  902. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->a_l, "matmul_q5_0_f32_aligned_l", matmul_q5_0_f32_aligned_fp32_len, matmul_q5_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  903. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->a_m, "matmul_q5_0_f32_aligned_m", matmul_q5_0_f32_aligned_fp32_len, matmul_q5_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  904. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0]->a_s, "matmul_q5_0_f32_aligned_s", matmul_q5_0_f32_aligned_fp32_len, matmul_q5_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  905. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->l, "matmul_q5_1_f32_l", matmul_q5_1_f32_fp32_len, matmul_q5_1_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  906. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->m, "matmul_q5_1_f32_m", matmul_q5_1_f32_fp32_len, matmul_q5_1_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  907. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->s, "matmul_q5_1_f32_s", matmul_q5_1_f32_fp32_len, matmul_q5_1_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  908. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->a_l, "matmul_q5_1_f32_aligned_l", matmul_q5_1_f32_aligned_fp32_len, matmul_q5_1_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  909. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->a_m, "matmul_q5_1_f32_aligned_m", matmul_q5_1_f32_aligned_fp32_len, matmul_q5_1_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  910. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1]->a_s, "matmul_q5_1_f32_aligned_s", matmul_q5_1_f32_aligned_fp32_len, matmul_q5_1_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  911. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->l, "matmul_q8_0_f32_l", matmul_q8_0_f32_fp32_len, matmul_q8_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  912. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->m, "matmul_q8_0_f32_m", matmul_q8_0_f32_fp32_len, matmul_q8_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  913. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->s, "matmul_q8_0_f32_s", matmul_q8_0_f32_fp32_len, matmul_q8_0_f32_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  914. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->a_l, "matmul_q8_0_f32_aligned_l", matmul_q8_0_f32_aligned_fp32_len, matmul_q8_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), l_wg_denoms, warptile_mmq_l, l_align);
  915. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->a_m, "matmul_q8_0_f32_aligned_m", matmul_q8_0_f32_aligned_fp32_len, matmul_q8_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), m_wg_denoms, warptile_mmq_m, m_align);
  916. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0]->a_s, "matmul_q8_0_f32_aligned_s", matmul_q8_0_f32_aligned_fp32_len, matmul_q8_0_f32_aligned_fp32_data, "main", 3, 14 * sizeof(uint32_t), s_wg_denoms, warptile_mmq_s, s_align);
  917. }
  918. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_F16 ], "mul_mat_vec_f16_f32", mul_mat_vec_f16_f32_len, mul_mat_vec_f16_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  919. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q4_0], "mul_mat_vec_q4_0_f32", mul_mat_vec_q4_0_f32_len, mul_mat_vec_q4_0_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  920. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q4_1], "mul_mat_vec_q4_1_f32", mul_mat_vec_q4_1_f32_len, mul_mat_vec_q4_1_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  921. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q5_0], "mul_mat_vec_q5_0_f32", mul_mat_vec_q5_0_f32_len, mul_mat_vec_q5_0_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  922. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q5_1], "mul_mat_vec_q5_1_f32", mul_mat_vec_q5_1_f32_len, mul_mat_vec_q5_1_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  923. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q8_0], "mul_mat_vec_q8_0_f32", mul_mat_vec_q8_0_f32_len, mul_mat_vec_q8_0_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  924. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q2_K], "mul_mat_vec_q2_K_f32", mul_mat_vec_q2_K_f32_len, mul_mat_vec_q2_K_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  925. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q3_K], "mul_mat_vec_q3_K_f32", mul_mat_vec_q3_K_f32_len, mul_mat_vec_q3_K_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  926. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q4_K], "mul_mat_vec_q4_K_f32", mul_mat_vec_q4_K_f32_len, mul_mat_vec_q4_K_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  927. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q5_K], "mul_mat_vec_q5_K_f32", mul_mat_vec_q5_K_f32_len, mul_mat_vec_q5_K_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  928. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_dequant_mul_mat_vec_f32[GGML_TYPE_Q6_K], "mul_mat_vec_q6_K_f32", mul_mat_vec_q6_K_f32_len, mul_mat_vec_q6_K_f32_data, "main", 3, 3 * sizeof(uint32_t), {1, 1, 1}, { device->subgroup_size }, 1);
  929. // dequant shaders
  930. ggml_vk_create_pipeline(ctx, ctx->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);
  931. ggml_vk_create_pipeline(ctx, ctx->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);
  932. ggml_vk_create_pipeline(ctx, ctx->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);
  933. ggml_vk_create_pipeline(ctx, ctx->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);
  934. ggml_vk_create_pipeline(ctx, ctx->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);
  935. ggml_vk_create_pipeline(ctx, ctx->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);
  936. ggml_vk_create_pipeline(ctx, ctx->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);
  937. ggml_vk_create_pipeline(ctx, ctx->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);
  938. ggml_vk_create_pipeline(ctx, ctx->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);
  939. ggml_vk_create_pipeline(ctx, ctx->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);
  940. ggml_vk_create_pipeline(ctx, ctx->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);
  941. // get_rows
  942. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_get_rows[GGML_TYPE_F16 ], "get_rows_f16", get_rows_f16_len, get_rows_f16_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  943. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  944. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  945. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  946. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  947. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  948. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_get_rows_f32[GGML_TYPE_F32 ], "get_rows_f16_f32", get_rows_f16_f32_len, get_rows_f16_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  949. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  950. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  951. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  952. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  953. ggml_vk_create_pipeline(ctx, ctx->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_push_constants), {512, 1, 1}, {}, 1);
  954. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256, 1, 1}, {}, 1);
  955. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, "mul_mat_vec_p021_f16_f32", mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", 3, 6 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  956. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", 3, 7 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  957. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_norm_f32, "norm_f32", norm_f32_len, norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  958. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  959. ggml_vk_create_pipeline(ctx, ctx->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);
  960. ggml_vk_create_pipeline(ctx, ctx->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);
  961. ggml_vk_create_pipeline(ctx, ctx->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);
  962. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_add_f32, "add_f32", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  963. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_mul_f32, "mul_f32", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  964. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_scale_f32, "scale_f32", scale_f32_len, scale_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  965. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_sqr_f32, "sqr_f32", sqr_f32_len, sqr_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  966. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_clamp_f32, "clamp_f32", clamp_f32_len, clamp_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  967. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_gelu_f32, "gelu_f32", gelu_f32_len, gelu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  968. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_silu_f32, "silu_f32", silu_f32_len, silu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  969. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_relu_f32, "relu_f32", relu_f32_len, relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  970. ggml_vk_create_pipeline(ctx, ctx->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), {512, 1, 1}, {}, 1);
  971. ggml_vk_create_pipeline(ctx, ctx->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}, {}, 1);
  972. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_rope_f32, "rope_f32", rope_f32_len, rope_f32_data, "main", 3, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  973. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_rope_f16, "rope_f16", rope_f16_len, rope_f16_data, "main", 3, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  974. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 3, sizeof(vk_op_rope_neox_push_constants), {1, 512, 1}, {}, 1);
  975. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 3, sizeof(vk_op_rope_neox_push_constants), {1, 512, 1}, {}, 1);
  976. ggml_vk_create_pipeline(ctx, ctx->device->pipeline_argsort_f32, "argsort_f32", argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1024, 1, 1}, {}, 1);
  977. }
  978. static void ggml_vk_print_gpu_info(size_t idx) {
  979. GGML_ASSERT(idx < vk_instance.device_indices.size());
  980. size_t dev_num = vk_instance.device_indices[idx];
  981. #ifdef GGML_VULKAN_DEBUG
  982. std::cerr << "ggml_vk_print_gpu_info(" << dev_num << ")" << std::endl;
  983. #endif
  984. GGML_ASSERT(vk_instance.initialized);
  985. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  986. if (dev_num >= devices.size()) {
  987. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  988. throw std::runtime_error("Device not found");
  989. }
  990. vk::PhysicalDevice physical_device = devices[dev_num];
  991. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  992. vk::PhysicalDeviceProperties2 props2;
  993. vk::PhysicalDeviceMaintenance3Properties props3;
  994. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  995. props2.pNext = &props3;
  996. props3.pNext = &subgroup_props;
  997. physical_device.getProperties2(&props2);
  998. const size_t subgroup_size = subgroup_props.subgroupSize;
  999. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  1000. bool fp16_storage = false;
  1001. bool fp16_compute = false;
  1002. for (auto properties : ext_props) {
  1003. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  1004. fp16_storage = true;
  1005. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  1006. fp16_compute = true;
  1007. }
  1008. }
  1009. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  1010. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  1011. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  1012. vk::PhysicalDeviceFeatures device_features = physical_device.getFeatures();
  1013. VkPhysicalDeviceFeatures2 device_features2;
  1014. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  1015. device_features2.pNext = nullptr;
  1016. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  1017. VkPhysicalDeviceVulkan11Features vk11_features;
  1018. vk11_features.pNext = nullptr;
  1019. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  1020. device_features2.pNext = &vk11_features;
  1021. VkPhysicalDeviceVulkan12Features vk12_features;
  1022. vk12_features.pNext = nullptr;
  1023. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  1024. vk11_features.pNext = &vk12_features;
  1025. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  1026. fp16 = fp16 && vk12_features.shaderFloat16;
  1027. std::string device_name = props2.properties.deviceName.data();
  1028. std::cerr << GGML_VK_NAME << idx << ": " << device_name << " | uma: " << uma << " | fp16: " << fp16 << " | warp size: " << subgroup_size << std::endl;
  1029. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  1030. std::cerr << "ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want." << std::endl;
  1031. }
  1032. }
  1033. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  1034. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  1035. void ggml_vk_instance_init() {
  1036. if (vk_instance_initialized) {
  1037. return;
  1038. }
  1039. #ifdef GGML_VULKAN_DEBUG
  1040. std::cerr << "ggml_vk_instance_init()" << std::endl;
  1041. #endif
  1042. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, VK_API_VERSION };
  1043. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  1044. const bool validation_ext = ggml_vk_instance_validation_ext_available(instance_extensions);
  1045. #ifdef __APPLE__
  1046. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  1047. #endif
  1048. std::vector<const char*> layers;
  1049. if (validation_ext) {
  1050. layers.push_back("VK_LAYER_KHRONOS_validation");
  1051. }
  1052. std::vector<const char*> extensions;
  1053. if (validation_ext) {
  1054. extensions.push_back("VK_EXT_validation_features");
  1055. }
  1056. #ifdef __APPLE__
  1057. if (portability_enumeration_ext) {
  1058. extensions.push_back("VK_KHR_portability_enumeration");
  1059. }
  1060. #endif
  1061. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  1062. #ifdef __APPLE__
  1063. if (portability_enumeration_ext) {
  1064. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  1065. }
  1066. #endif
  1067. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  1068. vk::ValidationFeaturesEXT validation_features;
  1069. if (validation_ext) {
  1070. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  1071. validation_features = {
  1072. features_enable,
  1073. {},
  1074. };
  1075. validation_features.setPNext(nullptr);
  1076. instance_create_info.setPNext(&validation_features);
  1077. std::cerr << "ggml_vulkan: Validation layers enabled" << std::endl;
  1078. }
  1079. vk_instance.instance = vk::createInstance(instance_create_info);
  1080. memset(vk_instance.initialized, 0, sizeof(bool) * GGML_VK_MAX_DEVICES);
  1081. size_t num_available_devices = vk_instance.instance.enumeratePhysicalDevices().size();
  1082. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  1083. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  1084. if (devices_env != nullptr) {
  1085. std::string devices(devices_env);
  1086. std::replace(devices.begin(), devices.end(), ',', ' ');
  1087. std::stringstream ss(devices);
  1088. size_t tmp;
  1089. while (ss >> tmp) {
  1090. if(tmp >= num_available_devices) {
  1091. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  1092. throw std::runtime_error("Invalid Vulkan device index");
  1093. }
  1094. vk_instance.device_indices.push_back(tmp);
  1095. }
  1096. } else {
  1097. vk_instance.device_indices.push_back(0);
  1098. }
  1099. vk_instance_initialized = true;
  1100. }
  1101. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  1102. GGML_ASSERT(idx < vk_instance.device_indices.size());
  1103. size_t dev_num = vk_instance.device_indices[idx];
  1104. #ifdef GGML_VULKAN_DEBUG
  1105. std::cerr << "ggml_vk_init(" << ctx->name << ", " << dev_num << ")" << std::endl;
  1106. #endif
  1107. ggml_vk_instance_init();
  1108. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  1109. if (dev_num >= devices.size()) {
  1110. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  1111. throw std::runtime_error("Device not found");
  1112. }
  1113. ctx->device = ggml_vk_get_device(idx);
  1114. if (!ctx->device->initialized) {
  1115. ctx->device->physical_device = devices[dev_num];
  1116. const std::vector<vk::ExtensionProperties> ext_props = ctx->device->physical_device.enumerateDeviceExtensionProperties();
  1117. bool maintenance4_support = false;
  1118. // Check if maintenance4 is supported
  1119. for (const auto& properties : ext_props) {
  1120. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  1121. maintenance4_support = true;
  1122. }
  1123. }
  1124. vk::PhysicalDeviceProperties2 props2;
  1125. vk::PhysicalDeviceMaintenance3Properties props3;
  1126. vk::PhysicalDeviceMaintenance4Properties props4;
  1127. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  1128. props2.pNext = &props3;
  1129. props3.pNext = &subgroup_props;
  1130. if (maintenance4_support) {
  1131. subgroup_props.pNext = &props4;
  1132. }
  1133. ctx->device->physical_device.getProperties2(&props2);
  1134. ctx->device->properties = props2.properties;
  1135. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  1136. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  1137. ctx->device->max_memory_allocation_size = std::stoi(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  1138. } else if (maintenance4_support) {
  1139. ctx->device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  1140. } else {
  1141. ctx->device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  1142. }
  1143. ctx->device->vendor_id = ctx->device->properties.vendorID;
  1144. ctx->device->subgroup_size = subgroup_props.subgroupSize;
  1145. ctx->device->uma = ctx->device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  1146. bool fp16_storage = false;
  1147. bool fp16_compute = false;
  1148. for (const auto& properties : ext_props) {
  1149. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  1150. fp16_storage = true;
  1151. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  1152. fp16_compute = true;
  1153. }
  1154. }
  1155. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  1156. const bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  1157. ctx->device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  1158. std::vector<vk::QueueFamilyProperties> queue_family_props = ctx->device->physical_device.getQueueFamilyProperties();
  1159. // Try to find a non-graphics compute queue and transfer-focused queues
  1160. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  1161. 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);
  1162. const float priorities[] = { 1.0f, 1.0f };
  1163. ctx->device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  1164. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  1165. if (compute_queue_family_index != transfer_queue_family_index) {
  1166. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1167. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  1168. } else if(!ctx->device->single_queue) {
  1169. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  1170. } else {
  1171. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1172. }
  1173. vk::DeviceCreateInfo device_create_info;
  1174. std::vector<const char *> device_extensions;
  1175. vk::PhysicalDeviceFeatures device_features = ctx->device->physical_device.getFeatures();
  1176. VkPhysicalDeviceFeatures2 device_features2;
  1177. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  1178. device_features2.pNext = nullptr;
  1179. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  1180. VkPhysicalDeviceVulkan11Features vk11_features;
  1181. vk11_features.pNext = nullptr;
  1182. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  1183. device_features2.pNext = &vk11_features;
  1184. VkPhysicalDeviceVulkan12Features vk12_features;
  1185. vk12_features.pNext = nullptr;
  1186. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  1187. vk11_features.pNext = &vk12_features;
  1188. vkGetPhysicalDeviceFeatures2(ctx->device->physical_device, &device_features2);
  1189. ctx->device->fp16 = ctx->device->fp16 && vk12_features.shaderFloat16;
  1190. if (!vk11_features.storageBuffer16BitAccess) {
  1191. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  1192. throw std::runtime_error("Unsupported device");
  1193. }
  1194. device_extensions.push_back("VK_KHR_16bit_storage");
  1195. #ifdef GGML_VULKAN_VALIDATE
  1196. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  1197. #endif
  1198. if (ctx->device->fp16) {
  1199. device_extensions.push_back("VK_KHR_shader_float16_int8");
  1200. }
  1201. ctx->device->name = ctx->device->properties.deviceName.data();
  1202. device_create_info = {
  1203. vk::DeviceCreateFlags(),
  1204. device_queue_create_infos,
  1205. {},
  1206. device_extensions
  1207. };
  1208. device_create_info.setPNext(&device_features2);
  1209. ctx->device->device = ctx->device->physical_device.createDevice(device_create_info);
  1210. ctx->device->descriptor_set_mode = VK_DEVICE_DESCRIPTOR_POOL_MODE_UNKNOWN;
  1211. // Queues
  1212. ggml_vk_create_queue(ctx, ctx->device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer });
  1213. // Shaders
  1214. ggml_vk_load_shaders(ctx);
  1215. if (!ctx->device->single_queue) {
  1216. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  1217. ggml_vk_create_queue(ctx, ctx->device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer });
  1218. } else {
  1219. // TODO: Use pointer or reference to avoid copy
  1220. ctx->device->transfer_queue = ctx->device->compute_queue;
  1221. }
  1222. ctx->device->idx = dev_num;
  1223. ctx->device->initialized = true;
  1224. } else if (ctx->device->idx != dev_num) {
  1225. std::cerr << "ggml_vulkan: Device " << ctx->device->name << " already initialized with index " << ctx->device->idx << ", but trying to reinitialize with index " << dev_num << std::endl;
  1226. throw std::runtime_error("Device already initialized");
  1227. }
  1228. ctx->fence = ctx->device->device.createFence({});
  1229. ctx->compute_ctx = nullptr;
  1230. ctx->transfer_ctx = nullptr;
  1231. ctx->disable = false;
  1232. ctx->initialized = true;
  1233. ctx->idx = idx;
  1234. #ifdef GGML_VULKAN_CHECK_RESULTS
  1235. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  1236. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  1237. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  1238. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  1239. #endif
  1240. }
  1241. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  1242. #ifdef GGML_VULKAN_DEBUG
  1243. std::cerr << "ggml_vk_get_to_fp16()" << std::endl;
  1244. #endif
  1245. switch (type) {
  1246. case GGML_TYPE_F32:
  1247. case GGML_TYPE_Q4_0:
  1248. case GGML_TYPE_Q4_1:
  1249. case GGML_TYPE_Q5_0:
  1250. case GGML_TYPE_Q5_1:
  1251. case GGML_TYPE_Q8_0:
  1252. case GGML_TYPE_Q2_K:
  1253. case GGML_TYPE_Q3_K:
  1254. case GGML_TYPE_Q4_K:
  1255. case GGML_TYPE_Q5_K:
  1256. case GGML_TYPE_Q6_K:
  1257. break;
  1258. default:
  1259. return nullptr;
  1260. }
  1261. return ctx->device->pipeline_dequant[type];
  1262. }
  1263. static vk_matmul_pipeline ggml_vk_get_mul_mat_mat_pipeline(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type) {
  1264. #ifdef GGML_VULKAN_DEBUG
  1265. std::cerr << "ggml_vk_get_mul_mat_mat_pipeline()" << std::endl;
  1266. #endif
  1267. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  1268. return ctx->device->pipeline_matmul_f32;
  1269. }
  1270. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  1271. return ctx->device->pipeline_matmul_f16_f32;
  1272. }
  1273. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  1274. return ctx->device->pipeline_matmul_f16;
  1275. }
  1276. GGML_ASSERT(src1_type == GGML_TYPE_F32);
  1277. switch (src0_type) {
  1278. case GGML_TYPE_Q4_0:
  1279. break;
  1280. default:
  1281. return nullptr;
  1282. }
  1283. return ctx->device->pipeline_dequant_mul_mat_mat[src0_type];
  1284. }
  1285. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type type) {
  1286. #ifdef GGML_VULKAN_DEBUG
  1287. std::cerr << "ggml_vk_get_dequantize_mul_mat_vec()" << std::endl;
  1288. #endif
  1289. switch (type) {
  1290. case GGML_TYPE_F16:
  1291. case GGML_TYPE_Q4_0:
  1292. case GGML_TYPE_Q4_1:
  1293. case GGML_TYPE_Q5_0:
  1294. case GGML_TYPE_Q5_1:
  1295. case GGML_TYPE_Q8_0:
  1296. case GGML_TYPE_Q2_K:
  1297. case GGML_TYPE_Q3_K:
  1298. case GGML_TYPE_Q4_K:
  1299. case GGML_TYPE_Q5_K:
  1300. case GGML_TYPE_Q6_K:
  1301. break;
  1302. default:
  1303. return nullptr;
  1304. }
  1305. return ctx->device->pipeline_dequant_mul_mat_vec_f32[type];
  1306. }
  1307. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  1308. #ifdef GGML_VULKAN_DEBUG
  1309. std::cerr << "ggml_vk_pool_malloc(" << size << ")" << std::endl;
  1310. #endif
  1311. int best_i = -1;
  1312. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  1313. int worst_i = -1;
  1314. size_t worst_size = 0; //largest unused buffer seen so far
  1315. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  1316. vk_buffer &b = ctx->buffer_pool[i];
  1317. if (b != nullptr && b->size >= size && b->size < best_size) {
  1318. best_i = i;
  1319. best_size = b->size;
  1320. }
  1321. if (b != nullptr && b->size > worst_size) {
  1322. worst_i = i;
  1323. worst_size = b->size;
  1324. }
  1325. }
  1326. if(best_i != -1) {
  1327. //found the smallest buffer that fits our needs
  1328. vk_buffer b = ctx->buffer_pool[best_i];
  1329. ctx->buffer_pool[best_i].reset();
  1330. return b;
  1331. }
  1332. if(worst_i != -1) {
  1333. //no buffer that fits our needs, resize largest one to save memory
  1334. vk_buffer& b = ctx->buffer_pool[worst_i];
  1335. ggml_vk_destroy_buffer(b);
  1336. }
  1337. return ggml_vk_create_buffer_check(ctx, size, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1338. }
  1339. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  1340. #ifdef GGML_VULKAN_DEBUG
  1341. std::cerr << "ggml_vk_pool_free(" << buffer->size << ")" << std::endl;
  1342. #endif
  1343. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  1344. vk_buffer& b = ctx->buffer_pool[i];
  1345. if (b == nullptr) {
  1346. b = buffer;
  1347. return;
  1348. }
  1349. }
  1350. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  1351. ggml_vk_destroy_buffer(buffer);
  1352. }
  1353. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  1354. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  1355. // Try to find existing temp buffer with enough capacity
  1356. for (auto& buffer : ctx->gc.temp_buffers) {
  1357. if (buffer->size >= size) {
  1358. return buffer;
  1359. }
  1360. }
  1361. // Otherwise create new buffer
  1362. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  1363. ctx->gc.temp_buffers.push_back(buf);
  1364. return buf;
  1365. }
  1366. static void * ggml_vk_host_malloc(ggml_backend_vk_context * ctx, size_t size) {
  1367. #ifdef GGML_VULKAN_DEBUG
  1368. std::cerr << "ggml_vk_host_malloc(" << size << ")" << std::endl;
  1369. #endif
  1370. vk_buffer buf = ggml_vk_create_buffer(ctx, size,
  1371. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  1372. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1373. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  1374. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  1375. size/1024.0/1024.0);
  1376. ctx->device->device.freeMemory(buf->device_memory);
  1377. ctx->device->device.destroyBuffer(buf->buffer);
  1378. return nullptr;
  1379. }
  1380. ctx->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  1381. return buf->ptr;
  1382. }
  1383. static void ggml_vk_host_free(ggml_backend_vk_context * ctx, void* ptr) {
  1384. if (ptr == nullptr) {
  1385. return;
  1386. }
  1387. #ifdef GGML_VULKAN_DEBUG
  1388. std::cerr << "ggml_vk_host_free(" << ptr << ")" << std::endl;
  1389. #endif
  1390. vk_buffer buf;
  1391. size_t index;
  1392. for (size_t i = 0; i < ctx->pinned_memory.size(); i++) {
  1393. const uint8_t* addr = (const uint8_t*) std::get<0>(ctx->pinned_memory[i]);
  1394. const uint8_t* endr = addr + std::get<1>(ctx->pinned_memory[i]);
  1395. if (ptr >= addr && ptr < endr) {
  1396. buf = std::get<2>(ctx->pinned_memory[i]);
  1397. index = i;
  1398. break;
  1399. }
  1400. }
  1401. if (buf == nullptr) {
  1402. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  1403. return;
  1404. }
  1405. ggml_vk_destroy_buffer(buf);
  1406. ctx->pinned_memory.erase(ctx->pinned_memory.begin() + index);
  1407. }
  1408. static void ggml_vk_host_get(ggml_backend_vk_context * ctx, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  1409. buf = nullptr;
  1410. buf_offset = 0;
  1411. for (size_t i = 0; i < ctx->pinned_memory.size(); i++) {
  1412. const uint8_t* addr = (const uint8_t*) std::get<0>(ctx->pinned_memory[i]);
  1413. const uint8_t* endr = addr + std::get<1>(ctx->pinned_memory[i]);
  1414. if (ptr >= addr && ptr < endr) {
  1415. buf = std::get<2>(ctx->pinned_memory[i]);
  1416. buf_offset = ((const uint8_t *)ptr) - addr;
  1417. break;
  1418. }
  1419. }
  1420. }
  1421. static vk_submission ggml_vk_begin_submission(ggml_backend_vk_context * ctx, vk_queue& q, bool one_time = true) {
  1422. vk_submission s;
  1423. s.buffer = ggml_vk_create_cmd_buffer(ctx, q);
  1424. if (one_time) {
  1425. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  1426. } else {
  1427. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  1428. }
  1429. return s;
  1430. }
  1431. static void ggml_vk_dispatch_pipeline(ggml_backend_vk_context * ctx, vk_context * subctx, vk_pipeline& pipeline, std::vector<vk_subbuffer>&& buffers, size_t push_constant_size, const void* push_constants, std::array<uint32_t, 3> elements) {
  1432. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  1433. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  1434. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  1435. #ifdef GGML_VULKAN_DEBUG
  1436. std::cerr << "ggml_vk_dispatch_pipeline(" << pipeline->name << ", (" << wg0 << "," << wg1 << "," << wg2 << "))" << std::endl;
  1437. #endif
  1438. std::vector<vk::DescriptorBufferInfo> descriptor_buffer_infos;
  1439. std::vector<vk::WriteDescriptorSet> write_descriptor_sets;
  1440. GGML_ASSERT(pipeline->descriptor_set_idx < pipeline->descriptor_sets.size());
  1441. GGML_ASSERT(buffers.size() == pipeline->parameter_count);
  1442. vk::DescriptorSet& descriptor_set = pipeline->descriptor_sets[pipeline->descriptor_set_idx++];
  1443. for (uint32_t i = 0; i < pipeline->parameter_count; i++) {
  1444. descriptor_buffer_infos.push_back({buffers[i].buffer->buffer, buffers[i].offset, buffers[i].size});
  1445. }
  1446. for (uint32_t i = 0; i < pipeline->parameter_count; i++) {
  1447. write_descriptor_sets.push_back({descriptor_set, i, 0, 1, vk::DescriptorType::eStorageBuffer, nullptr, &descriptor_buffer_infos[i]});
  1448. }
  1449. ctx->device->device.updateDescriptorSets(write_descriptor_sets, {});
  1450. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size, push_constants);
  1451. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  1452. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  1453. pipeline->layout,
  1454. 0,
  1455. { descriptor_set },
  1456. {});
  1457. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  1458. }
  1459. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  1460. s.buffer.end();
  1461. s.wait_semaphores = std::move(wait_semaphores);
  1462. s.signal_semaphores = std::move(signal_semaphores);
  1463. }
  1464. static void ggml_vk_ctx_end(vk_context * ctx) {
  1465. #ifdef GGML_VULKAN_DEBUG
  1466. std::cerr << "ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")" << std::endl;
  1467. #endif
  1468. if (ctx->s == nullptr) {
  1469. return;
  1470. }
  1471. ctx->s->buffer.end();
  1472. ctx->s = nullptr;
  1473. }
  1474. static void ggml_vk_ctx_begin(ggml_backend_vk_context * ctx, vk_context * subctx) {
  1475. #ifdef GGML_VULKAN_DEBUG
  1476. std::cerr << "ggml_vk_ctx_begin(" << ctx << ")" << std::endl;
  1477. #endif
  1478. if (subctx->s != nullptr) {
  1479. ggml_vk_ctx_end(subctx);
  1480. }
  1481. subctx->seqs.push_back({ ggml_vk_begin_submission(ctx, *subctx->q) });
  1482. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  1483. }
  1484. static size_t ggml_vk_align_size(size_t width, size_t align) {
  1485. return CEIL_DIV(width, align) * align;
  1486. }
  1487. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  1488. if (memcpys == nullptr) {
  1489. memcpy(dst, src, size);
  1490. } else {
  1491. memcpys->emplace_back(dst, src, size);
  1492. }
  1493. }
  1494. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  1495. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  1496. ggml_vk_destroy_buffer(ctx->sync_staging);
  1497. ctx->sync_staging = ggml_vk_create_buffer_check(ctx, size,
  1498. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  1499. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1500. }
  1501. }
  1502. 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) {
  1503. #ifdef GGML_VULKAN_DEBUG
  1504. std::cerr << "ggml_vk_buffer_write_nc_async(" << tensor << ")" << std::endl;
  1505. #endif
  1506. GGML_ASSERT(!ggml_is_contiguous(tensor));
  1507. // Buffer is already mapped
  1508. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1509. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  1510. GGML_ASSERT(false);
  1511. }
  1512. // Check if src is pinned memory
  1513. vk_buffer buf;
  1514. size_t buf_offset;
  1515. ggml_vk_host_get(ctx, tensor->data, buf, buf_offset);
  1516. const uint64_t ne0 = tensor->ne[0];
  1517. const uint64_t ne1 = tensor->ne[1];
  1518. const uint64_t ne2 = tensor->ne[2];
  1519. const uint64_t ne3 = tensor->ne[3];
  1520. const uint64_t nb0 = tensor->nb[0];
  1521. const uint64_t nb1 = tensor->nb[1];
  1522. const uint64_t nb2 = tensor->nb[2];
  1523. const uint64_t nb3 = tensor->nb[3];
  1524. const ggml_type type = tensor->type;
  1525. const uint64_t ts = ggml_type_size(type);
  1526. const uint64_t bs = ggml_blck_size(type);
  1527. const uint64_t dstnb0 = ts;
  1528. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  1529. const uint64_t dstnb2 = dstnb1*ne1;
  1530. const uint64_t dstnb3 = dstnb2*ne2;
  1531. const uint64_t ne = ggml_nelements(tensor);
  1532. if (buf != nullptr) {
  1533. // Memory is pinned, use as staging buffer
  1534. std::vector<vk::BufferCopy> slices;
  1535. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  1536. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  1537. // Find longest contiguous slice
  1538. if (ne1*nb1 == dstnb2) {
  1539. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  1540. } else {
  1541. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  1542. if (ne0*nb0/bs == dstnb1) {
  1543. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  1544. } else {
  1545. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  1546. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  1547. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  1548. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  1549. }
  1550. }
  1551. }
  1552. }
  1553. }
  1554. }
  1555. ggml_vk_sync_buffers(subctx);
  1556. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  1557. return;
  1558. }
  1559. // Staging buffer required
  1560. vk_buffer staging = ctx->staging;
  1561. size_t staging_offset = ctx->staging_offset;
  1562. const size_t copy_size = ts*ne/bs;
  1563. if (ctx->staging->size < ctx->staging_offset + copy_size) {
  1564. if (sync_staging) {
  1565. // Create temporary larger buffer
  1566. ggml_vk_ensure_sync_staging_buffer(ctx, copy_size);
  1567. staging = ctx->sync_staging;
  1568. staging_offset = 0;
  1569. } else {
  1570. GGML_ASSERT(false);
  1571. }
  1572. }
  1573. VkBufferCopy buf_copy{ staging_offset, offset, copy_size };
  1574. ggml_vk_sync_buffers(subctx);
  1575. vkCmdCopyBuffer(subctx->s->buffer, staging->buffer, dst->buffer, 1, &buf_copy);
  1576. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  1577. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  1578. // Find longest contiguous slice
  1579. if (ne1*nb1 == dstnb2) {
  1580. deferred_memcpy((uint8_t *)staging->ptr + staging_offset + i3*dstnb3 + i2*dstnb2, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2, dstnb2, &subctx->in_memcpys);
  1581. } else {
  1582. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  1583. if (ne0*nb0/bs == dstnb1) {
  1584. deferred_memcpy((uint8_t *)staging->ptr + staging_offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2 + i1*nb1, dstnb1, &subctx->in_memcpys);
  1585. } else {
  1586. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  1587. const uint64_t d_off = staging_offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  1588. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  1589. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  1590. }
  1591. }
  1592. }
  1593. }
  1594. }
  1595. }
  1596. }
  1597. static void ggml_vk_buffer_write_2d_async(ggml_backend_vk_context * ctx, 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) {
  1598. #ifdef GGML_VULKAN_DEBUG
  1599. std::cerr << "ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")" << std::endl;
  1600. #endif
  1601. // Make sure ctx owns the buffer
  1602. GGML_ASSERT(dst->ctx == ctx);
  1603. // Buffer is already mapped
  1604. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1605. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  1606. GGML_ASSERT(false);
  1607. }
  1608. // Check if src is pinned memory
  1609. vk_buffer buf = nullptr;
  1610. size_t buf_offset;
  1611. ggml_vk_host_get(ctx, src, buf, buf_offset);
  1612. if (buf != nullptr) {
  1613. // Memory is pinned, use as staging buffer
  1614. std::vector<vk::BufferCopy> slices(1);
  1615. if (width == spitch) {
  1616. // Only do single write if stride is equal
  1617. slices[0].srcOffset = buf_offset;
  1618. slices[0].dstOffset = offset;
  1619. slices[0].size = width * height;
  1620. } else {
  1621. slices.resize(height);
  1622. for (size_t i = 0; i < height; i++) {
  1623. slices[i].srcOffset = buf_offset + i * spitch;
  1624. slices[i].dstOffset = offset + i * width;
  1625. slices[i].size = width;
  1626. }
  1627. }
  1628. ggml_vk_sync_buffers(subctx);
  1629. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  1630. return;
  1631. }
  1632. #ifdef GGML_VULKAN_DEBUG
  1633. std::cerr << "STAGING" << std::endl;
  1634. #endif
  1635. // Staging buffer required
  1636. vk_buffer staging = ctx->staging;
  1637. size_t staging_offset = ctx->staging_offset;
  1638. const size_t copy_size = width*height;
  1639. if (ctx->staging == nullptr || ctx->staging->size < ctx->staging_offset + copy_size) {
  1640. if (sync_staging) {
  1641. ggml_vk_ensure_sync_staging_buffer(ctx, copy_size);
  1642. staging = ctx->sync_staging;
  1643. staging_offset = 0;
  1644. } else {
  1645. GGML_ASSERT(false);
  1646. }
  1647. }
  1648. VkBufferCopy buf_copy = {
  1649. staging_offset,
  1650. offset,
  1651. copy_size};
  1652. ggml_vk_sync_buffers(subctx);
  1653. vkCmdCopyBuffer(subctx->s->buffer, staging->buffer, dst->buffer, 1, &buf_copy);
  1654. if (width == spitch) {
  1655. deferred_memcpy((uint8_t *)staging->ptr + staging_offset, src, width * height, &subctx->in_memcpys);
  1656. } else {
  1657. for (size_t i = 0; i < height; i++) {
  1658. deferred_memcpy((uint8_t *)staging->ptr + staging_offset + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  1659. }
  1660. }
  1661. }
  1662. static void ggml_vk_buffer_write_async(ggml_backend_vk_context * ctx, vk_context * subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  1663. #ifdef GGML_VULKAN_DEBUG
  1664. std::cerr << "ggml_vk_buffer_write_async(" << size << ")" << std::endl;
  1665. #endif
  1666. return ggml_vk_buffer_write_2d_async(ctx, subctx, dst, offset, src, size, size, 1, sync_staging);
  1667. }
  1668. static void ggml_vk_buffer_write_2d(ggml_backend_vk_context * ctx, vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height) {
  1669. #ifdef GGML_VULKAN_DEBUG
  1670. std::cerr << "ggml_vk_buffer_write_2d(" << width << ", " << height << ")" << std::endl;
  1671. #endif
  1672. // Buffer is already mapped
  1673. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1674. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  1675. for (size_t i = 0; i < height; i++) {
  1676. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  1677. }
  1678. } else {
  1679. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  1680. ggml_vk_ctx_begin(ctx, subctx);
  1681. ggml_vk_buffer_write_2d_async(ctx, subctx, dst, offset, src, spitch, width, height, true);
  1682. ggml_vk_ctx_end(subctx);
  1683. for (auto& cpy : subctx->in_memcpys) {
  1684. memcpy(cpy.dst, cpy.src, cpy.n);
  1685. }
  1686. ggml_vk_submit(subctx, ctx->fence);
  1687. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  1688. ctx->device->device.resetFences({ ctx->fence });
  1689. ggml_vk_queue_cleanup(ctx, ctx->device->transfer_queue);
  1690. }
  1691. }
  1692. static void ggml_vk_buffer_write(ggml_backend_vk_context * ctx, vk_buffer& dst, size_t offset, const void * src, size_t size) {
  1693. #ifdef GGML_VULKAN_DEBUG
  1694. std::cerr << "ggml_vk_buffer_write(" << size << ")" << std::endl;
  1695. #endif
  1696. ggml_vk_buffer_write_2d(ctx, dst, offset, src, 0, size, 1);
  1697. }
  1698. static void ggml_vk_buffer_read_2d_async(ggml_backend_vk_context * ctx, 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) {
  1699. #ifdef GGML_VULKAN_DEBUG
  1700. std::cerr << "ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")" << std::endl;
  1701. #endif
  1702. GGML_ASSERT(width > 0);
  1703. GGML_ASSERT(height > 0);
  1704. GGML_ASSERT(src != nullptr);
  1705. // Make sure ctx owns the buffer
  1706. GGML_ASSERT(src->ctx == ctx);
  1707. // Check if dst is pinned memory
  1708. vk_buffer buf = nullptr;
  1709. size_t buf_offset;
  1710. ggml_vk_host_get(ctx, dst, buf, buf_offset);
  1711. std::vector<vk::BufferCopy> slices(1);
  1712. if (width == spitch && width == dpitch) {
  1713. // Only do single write if stride is equal
  1714. slices[0].srcOffset = offset;
  1715. slices[0].dstOffset = buf_offset;
  1716. slices[0].size = width * height;
  1717. } else {
  1718. slices.resize(height);
  1719. for (size_t i = 0; i < height; i++) {
  1720. slices[i].srcOffset = offset + i * spitch;
  1721. slices[i].dstOffset = buf_offset + i * dpitch;
  1722. slices[i].size = width;
  1723. }
  1724. }
  1725. if (buf != nullptr) {
  1726. // Memory is pinned, use as staging buffer
  1727. ggml_vk_sync_buffers(subctx);
  1728. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  1729. return;
  1730. }
  1731. #ifdef GGML_VULKAN_DEBUG
  1732. std::cerr << "STAGING" << std::endl;
  1733. #endif
  1734. // Fall back to staging buffer
  1735. vk_buffer staging = ctx->staging;
  1736. const size_t copy_size = dpitch * height;
  1737. if (ctx->staging == nullptr || ctx->staging->size < ctx->staging_offset + copy_size) {
  1738. if (sync_staging) {
  1739. // Create temporary larger buffer
  1740. ggml_vk_ensure_sync_staging_buffer(ctx, copy_size);
  1741. staging = ctx->sync_staging;
  1742. } else {
  1743. GGML_ASSERT(false);
  1744. }
  1745. }
  1746. ggml_vk_sync_buffers(subctx);
  1747. subctx->s->buffer.copyBuffer(src->buffer, staging->buffer, slices);
  1748. deferred_memcpy(dst, staging->ptr, copy_size, &subctx->out_memcpys);
  1749. }
  1750. static void ggml_vk_buffer_read_async(ggml_backend_vk_context * ctx, vk_context * subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  1751. return ggml_vk_buffer_read_2d_async(ctx, subctx, src, offset, dst, size, size, size, 1, sync_staging);
  1752. }
  1753. static void ggml_vk_buffer_read(ggml_backend_vk_context * ctx, vk_buffer& src, size_t offset, void * dst, size_t size) {
  1754. #ifdef GGML_VULKAN_DEBUG
  1755. std::cerr << "ggml_vk_buffer_read(" << offset << ", " << size << ")" << std::endl;
  1756. #endif
  1757. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1758. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  1759. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  1760. } else {
  1761. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  1762. ggml_vk_ctx_begin(ctx, subctx);
  1763. ggml_vk_buffer_read_async(ctx, subctx, src, offset, dst, size, true);
  1764. ggml_vk_ctx_end(subctx);
  1765. ggml_vk_submit(subctx, ctx->fence);
  1766. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  1767. ctx->device->device.resetFences({ ctx->fence });
  1768. for (auto& cpy : subctx->out_memcpys) {
  1769. memcpy(cpy.dst, cpy.src, cpy.n);
  1770. }
  1771. ggml_vk_queue_cleanup(ctx, ctx->device->transfer_queue);
  1772. }
  1773. }
  1774. 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) {
  1775. #ifdef GGML_VULKAN_DEBUG
  1776. std::cerr << "ggml_vk_buffer_copy_async(" << size << ")" << std::endl;
  1777. #endif
  1778. // Make sure both buffers are on same ctx
  1779. GGML_ASSERT(src->ctx == dst->ctx);
  1780. VkBufferCopy bc{ src_offset, dst_offset, size };
  1781. vkCmdCopyBuffer(ctx->s->buffer, src->buffer, dst->buffer, 1, &bc);
  1782. }
  1783. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  1784. if (src->ctx == dst->ctx) {
  1785. #ifdef GGML_VULKAN_DEBUG
  1786. std::cerr << "ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")" << std::endl;
  1787. #endif
  1788. // Copy within the device
  1789. ggml_backend_vk_context * ctx = src->ctx;
  1790. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  1791. ggml_vk_ctx_begin(ctx, subctx);
  1792. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  1793. ggml_vk_ctx_end(subctx);
  1794. ggml_vk_submit(subctx, ctx->fence);
  1795. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  1796. ctx->device->device.resetFences({ ctx->fence });
  1797. } else {
  1798. #ifdef GGML_VULKAN_DEBUG
  1799. std::cerr << "ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")" << std::endl;
  1800. #endif
  1801. // Copy device to device
  1802. ggml_backend_vk_context * src_ctx = src->ctx;
  1803. ggml_backend_vk_context * dst_ctx = dst->ctx;
  1804. ggml_vk_ensure_sync_staging_buffer(src_ctx, size);
  1805. ggml_vk_ensure_sync_staging_buffer(dst_ctx, size);
  1806. // Copy to src staging buffer
  1807. ggml_vk_buffer_copy(src_ctx->sync_staging, 0, src, src_offset, size);
  1808. // memcpy to dst staging buffer
  1809. memcpy(dst_ctx->sync_staging->ptr, src_ctx->sync_staging->ptr, size);
  1810. // Copy to dst buffer
  1811. ggml_vk_buffer_copy(dst, dst_offset, dst_ctx->sync_staging, 0, size);
  1812. }
  1813. }
  1814. static void ggml_vk_buffer_memset(ggml_backend_vk_context * ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  1815. #ifdef GGML_VULKAN_DEBUG
  1816. std::cerr << "ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")" << std::endl;
  1817. #endif
  1818. // Make sure ctx owns the buffer
  1819. GGML_ASSERT(dst->ctx == ctx);
  1820. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  1821. ggml_vk_ctx_begin(ctx, subctx);
  1822. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  1823. ggml_vk_ctx_end(subctx);
  1824. ggml_vk_submit(subctx, ctx->fence);
  1825. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  1826. ctx->device->device.resetFences({ ctx->fence });
  1827. }
  1828. static void ggml_vk_h2d_tensor_2d(ggml_backend_vk_context * ctx, vk_context * subctx, vk_buffer& dst, size_t offset, const ggml_tensor * src, uint64_t i3, uint64_t i2, uint64_t i1) {
  1829. #ifdef GGML_VULKAN_DEBUG
  1830. std::cerr << "ggml_vk_h2d_tensor_2d(dst=" << dst << ", offset=" << offset << ", src=" << src << ", i3=" << i3 << ", i2=" << i2 << ", i1=" << i1 << ")" << std::endl;
  1831. #endif
  1832. const uint64_t ne0 = src->ne[0];
  1833. const uint64_t ne1 = src->ne[1];
  1834. const uint64_t nb0 = src->nb[0];
  1835. const uint64_t nb1 = src->nb[1];
  1836. const uint64_t nb2 = src->nb[2];
  1837. const uint64_t nb3 = src->nb[3];
  1838. const enum ggml_type type = src->type;
  1839. const size_t ts = ggml_type_size(type);
  1840. const size_t bs = ggml_blck_size(type);
  1841. const size_t row_length = ts*ne0/bs;
  1842. const void * x = (const void *) ((const char *) src->data + i2*nb2 + i3*nb3);
  1843. if (nb0 == ts && nb1 == row_length) {
  1844. return ggml_vk_buffer_write_async(ctx, subctx, dst, offset, x, i1*nb1);
  1845. }
  1846. if (nb0 == ts && (i1 == ne1 || !ggml_is_permuted(src))) {
  1847. return ggml_vk_buffer_write_2d_async(ctx, subctx, dst, offset, x, nb1, row_length, i1);
  1848. }
  1849. GGML_ASSERT(i3 == 0);
  1850. GGML_ASSERT(i2 == 0);
  1851. GGML_ASSERT(i1 == (uint64_t) ggml_nrows(src));
  1852. return ggml_vk_buffer_write_nc_async(ctx, subctx, dst, offset, src);
  1853. }
  1854. static void ggml_vk_d2h_tensor_2d(ggml_backend_vk_context * ctx, vk_context * subctx, vk_buffer& src, size_t offset, const ggml_tensor * dst) {
  1855. #ifdef GGML_VULKAN_DEBUG
  1856. std::cerr << "ggml_vk_d2h_tensor_2d()" << std::endl;
  1857. #endif
  1858. const uint64_t ne0 = dst->ne[0];
  1859. const uint64_t ne1 = dst->ne[1];
  1860. const uint64_t ne2 = dst->ne[2];
  1861. const uint64_t ne3 = dst->ne[3];
  1862. const uint64_t nb0 = dst->nb[0];
  1863. const uint64_t nb1 = dst->nb[1];
  1864. // const uint64_t nb2 = dst->nb[2];
  1865. // const uint64_t nb3 = dst->nb[3];
  1866. const enum ggml_type type = dst->type;
  1867. const size_t ts = ggml_type_size(type);
  1868. const size_t bs = ggml_blck_size(type);
  1869. const size_t row_length = ts*ne0/bs;
  1870. if (ggml_is_contiguous(dst)) {
  1871. return ggml_vk_buffer_read_async(ctx, subctx, src, offset, dst->data, ne1*nb1*ne2*ne3);
  1872. }
  1873. if (nb0 == ts) {
  1874. return ggml_vk_buffer_read_2d_async(ctx, subctx, src, offset, dst->data, nb1, nb1, row_length, ne1*ne2*ne3);
  1875. }
  1876. GGML_ASSERT(false);
  1877. }
  1878. static uint32_t ggml_vk_guess_split_k(int m, int n, int k) {
  1879. #ifdef GGML_VULKAN_DEBUG
  1880. std::cerr << "ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ")" << std::endl;
  1881. #endif
  1882. if (k > 128 && (m < 128 || n < 128) && m > 2 && n > 2) {
  1883. return 4;
  1884. }
  1885. return 1;
  1886. }
  1887. static vk_pipeline ggml_vk_guess_matmul_pipeline_amd(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  1888. if (m <= 32 || n <= 32) {
  1889. return aligned ? mmp->a_s : mmp->s;
  1890. }
  1891. return aligned ? mmp->a_m : mmp->m;
  1892. GGML_UNUSED(ctx);
  1893. }
  1894. static vk_pipeline ggml_vk_guess_matmul_pipeline_apple(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, bool aligned) {
  1895. return aligned ? mmp->a_m : mmp->m;
  1896. GGML_UNUSED(ctx);
  1897. }
  1898. static vk_pipeline ggml_vk_guess_matmul_pipeline_intel(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, bool aligned) {
  1899. return aligned ? mmp->a_s : mmp->s;
  1900. GGML_UNUSED(ctx);
  1901. }
  1902. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  1903. #ifdef GGML_VULKAN_DEBUG
  1904. std::cerr << "ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")" << std::endl;
  1905. #endif
  1906. switch (ctx->device->vendor_id) {
  1907. case VK_VENDOR_ID_AMD:
  1908. return ggml_vk_guess_matmul_pipeline_amd(ctx, mmp, m, n, aligned);
  1909. case VK_VENDOR_ID_APPLE:
  1910. return ggml_vk_guess_matmul_pipeline_apple(ctx, mmp, aligned);
  1911. case VK_VENDOR_ID_INTEL:
  1912. return ggml_vk_guess_matmul_pipeline_intel(ctx, mmp, aligned);
  1913. }
  1914. if (m <= 32 || n <= 32) {
  1915. return aligned ? mmp->a_s : mmp->s;
  1916. }
  1917. if (m <= 64 || n <= 64) {
  1918. return aligned ? mmp->a_m : mmp->m;
  1919. }
  1920. return aligned ? mmp->a_l : mmp->l;
  1921. }
  1922. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n) {
  1923. #ifdef GGML_VULKAN_DEBUG
  1924. std::cerr << "ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")" << std::endl;
  1925. #endif
  1926. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, false)->align;
  1927. }
  1928. static void ggml_vk_matmul(ggml_backend_vk_context * ctx, vk_context * subctx, vk_pipeline& pipeline, vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer, uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d, uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3, uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d) {
  1929. #ifdef GGML_VULKAN_DEBUG
  1930. std::cerr << "ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), c: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << split_k_buffer.buffer->buffer << ", " << 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 << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ")" << std::endl;
  1931. #endif
  1932. ggml_vk_sync_buffers(subctx);
  1933. if (split_k == 1) {
  1934. const std::array<uint32_t, 14> pc = { m, n, k, stride_a, stride_b, stride_d, k, ne02, ne12, broadcast2, broadcast3, batch_stride_a, batch_stride_b, batch_stride_d };
  1935. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc.size() * sizeof(uint32_t), pc.data(), { m, n, batch });
  1936. return;
  1937. }
  1938. GGML_ASSERT(batch_stride_d == m * n);
  1939. const std::array<uint32_t, 14> pc1 = { m, n, k, stride_a, stride_b, stride_d, CEIL_DIV(k, split_k), ne02, ne12, broadcast2, broadcast3, batch_stride_a, batch_stride_b, batch_stride_d };
  1940. // Make sure enough workgroups get assigned for split k to work
  1941. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, pc1.size() * sizeof(uint32_t), pc1.data(), { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  1942. ggml_vk_sync_buffers(subctx);
  1943. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  1944. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2.size() * sizeof(uint32_t), pc2.data(), { m * n * batch, 1, 1 });
  1945. }
  1946. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  1947. return
  1948. tensor->nb[0] == ggml_type_size(tensor->type) &&
  1949. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  1950. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  1951. }
  1952. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, ggml_type from, ggml_type to) {
  1953. if (from == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  1954. return ctx->device->pipeline_cpy_f32_f32;
  1955. }
  1956. if (from == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  1957. return ctx->device->pipeline_cpy_f32_f16;
  1958. }
  1959. if (from == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  1960. return ctx->device->pipeline_cpy_f16_f16;
  1961. }
  1962. std::cerr << "Missing CPY op for types: " << ggml_type_name(from) << " " << ggml_type_name(to) << std::endl;
  1963. GGML_ASSERT(false);
  1964. }
  1965. 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) {
  1966. #ifdef GGML_VULKAN_DEBUG
  1967. std::cerr << "ggml_vk_cpy_to_contiguous((" << tensor << ", type=" << tensor->type << ", backend=" << tensor->backend << ", 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] << "), ";
  1968. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")" << std::endl;
  1969. #endif
  1970. const int tensor_type_size = ggml_type_size(tensor->type);
  1971. const uint32_t ne = ggml_nelements(tensor);
  1972. const vk_op_unary_push_constants pc = {
  1973. (uint32_t)ne,
  1974. (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,
  1975. (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]),
  1976. 0,
  1977. 0.0f, 0.0f,
  1978. };
  1979. ggml_vk_sync_buffers(subctx);
  1980. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, sizeof(vk_op_unary_push_constants), &pc, { ne, 1, 1 });
  1981. }
  1982. 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) {
  1983. #ifdef GGML_VULKAN_DEBUG
  1984. std::cerr << "ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  1985. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  1986. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "),)" << std::endl;
  1987. #endif
  1988. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  1989. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  1990. const uint64_t ne00 = src0->ne[0];
  1991. const uint64_t ne01 = src0->ne[1];
  1992. const uint64_t ne02 = src0->ne[2];
  1993. const uint64_t ne03 = src0->ne[3];
  1994. const uint64_t ne10 = src1->ne[0];
  1995. const uint64_t ne11 = src1->ne[1];
  1996. const uint64_t ne12 = src1->ne[2];
  1997. const uint64_t ne13 = src1->ne[3];
  1998. const uint64_t ne20 = dst->ne[0];
  1999. const uint64_t ne21 = dst->ne[1];
  2000. const uint64_t r2 = ne12 / ne02;
  2001. const uint64_t r3 = ne13 / ne03;
  2002. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2003. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2004. ggml_tensor_extra_gpu * extra_src1 = (ggml_tensor_extra_gpu *) src1->extra;
  2005. vk_buffer d_Qx;
  2006. size_t qx_buf_offset = 0;
  2007. vk_buffer d_Qy;
  2008. size_t qy_buf_offset = 0;
  2009. bool src0_uma = false;
  2010. bool src1_uma = false;
  2011. if (ctx->device->uma) {
  2012. ggml_vk_host_get(ctx, src0->data, d_Qx, qx_buf_offset);
  2013. ggml_vk_host_get(ctx, src1->data, d_Qy, qy_buf_offset);
  2014. src0_uma = d_Qx != nullptr;
  2015. src1_uma = d_Qy != nullptr;
  2016. }
  2017. const bool load_x = src0->backend != GGML_BACKEND_TYPE_GPU && !src0_uma;
  2018. const bool load_y = src1->backend != GGML_BACKEND_TYPE_GPU && !src1_uma;
  2019. const bool x_non_contig = !load_x && !ggml_vk_dim01_contiguous(src0);
  2020. const bool y_non_contig = !load_y && !ggml_vk_dim01_contiguous(src1);
  2021. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  2022. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type);
  2023. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  2024. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  2025. if (mmp == nullptr) {
  2026. // Fall back to dequant + f16 mulmat
  2027. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, GGML_TYPE_F16, y_f32_kernel ? GGML_TYPE_F32 : GGML_TYPE_F16);
  2028. }
  2029. // Not implemented
  2030. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  2031. const int x_ne = ne01 * ne00;
  2032. const int y_ne = ne11 * ne10;
  2033. const int d_ne = ne11 * ne01;
  2034. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11));
  2035. const bool aligned = ne10 == kpad;
  2036. const uint32_t split_k = ggml_vk_guess_split_k(ne01, ne11, ne10);
  2037. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned);
  2038. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  2039. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  2040. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  2041. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  2042. const uint64_t d_sz = sizeof(float) * d_ne;
  2043. vk_buffer d_D = extra->buffer_gpu.lock();
  2044. const uint64_t d_buf_offset = extra->offset;
  2045. GGML_ASSERT(d_D != nullptr);
  2046. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  2047. vk_buffer d_X;
  2048. uint64_t x_buf_offset = 0;
  2049. vk_buffer d_Y;
  2050. uint64_t y_buf_offset = 0;
  2051. if (load_x) {
  2052. d_Qx = ctx->prealloc_qx;
  2053. } else if (!src0_uma) {
  2054. d_Qx = extra_src0->buffer_gpu.lock();
  2055. qx_buf_offset = extra_src0->offset;
  2056. GGML_ASSERT(d_Qx != nullptr);
  2057. }
  2058. if (load_y) {
  2059. d_Qy = ctx->prealloc_qy;
  2060. } else if (!src1_uma) {
  2061. d_Qy = extra_src1->buffer_gpu.lock();
  2062. qy_buf_offset = extra_src1->offset;
  2063. GGML_ASSERT(d_Qy != nullptr);
  2064. }
  2065. if (qx_needs_dequant) {
  2066. d_X = ctx->prealloc_x;
  2067. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  2068. } else {
  2069. d_X = d_Qx;
  2070. x_buf_offset = qx_buf_offset;
  2071. GGML_ASSERT(qx_sz == x_sz);
  2072. }
  2073. if (qy_needs_dequant) {
  2074. d_Y = ctx->prealloc_y;
  2075. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  2076. } else {
  2077. d_Y = d_Qy;
  2078. y_buf_offset = qy_buf_offset;
  2079. GGML_ASSERT(qy_sz == y_sz);
  2080. }
  2081. vk_pipeline to_fp16_vk_0 = nullptr;
  2082. vk_pipeline to_fp16_vk_1 = nullptr;
  2083. if (x_non_contig) {
  2084. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0->type, GGML_TYPE_F16);
  2085. } else {
  2086. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  2087. }
  2088. if (y_non_contig) {
  2089. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1->type, GGML_TYPE_F16);
  2090. } else {
  2091. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  2092. }
  2093. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  2094. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  2095. // Allocate descriptor sets
  2096. ggml_pipeline_allocate_descriptor_sets(ctx, pipeline, 1);
  2097. if (qx_needs_dequant) {
  2098. ggml_pipeline_allocate_descriptor_sets(ctx, to_fp16_vk_0, 1);
  2099. }
  2100. if (qy_needs_dequant) {
  2101. ggml_pipeline_allocate_descriptor_sets(ctx, to_fp16_vk_1, 1);
  2102. }
  2103. if (split_k > 1) {
  2104. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  2105. }
  2106. if (x_non_contig) {
  2107. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  2108. } else if (load_x || qx_needs_dequant) {
  2109. if (load_x) {
  2110. // copy data to device
  2111. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qx, 0, src0, 0, 0, ggml_nrows(src0));
  2112. ctx->staging_offset = qx_sz * ne02 * ne03;
  2113. }
  2114. if (qx_needs_dequant) {
  2115. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  2116. ggml_vk_sync_buffers(subctx);
  2117. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { { d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, { d_X, 0, x_sz * ne02 * ne03 } }, pc.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  2118. }
  2119. }
  2120. if (y_non_contig) {
  2121. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  2122. } else if (load_y) {
  2123. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qy, 0, src1, 0, 0, ggml_nrows(src1));
  2124. }
  2125. uint32_t stride_batch_x = ne00*ne01;
  2126. uint32_t stride_batch_y = ne10*ne11;
  2127. if (!ggml_vk_dim01_contiguous(src0) && !load_x && !qx_needs_dequant) {
  2128. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  2129. }
  2130. if (!ggml_vk_dim01_contiguous(src1) && !load_y && !qy_needs_dequant) {
  2131. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  2132. }
  2133. // compute
  2134. ggml_vk_matmul(ctx, subctx, pipeline, { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 }, { d_D, d_buf_offset, d_sz * ne12 * ne13 }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k }, ne01, ne11, ne10, ne10, ne10, ne01, split_k, ne12*ne13, ne02, ne12, r2, r3, stride_batch_x, stride_batch_y, ne20*ne21); // NOLINT
  2135. if (dst->backend == GGML_BACKEND_TYPE_CPU) {
  2136. // copy dst to host
  2137. float * d = (float *) ((char *) dst->data);
  2138. ggml_vk_buffer_read_async(ctx, subctx, d_D, 0, d, sizeof(float) * d_ne * ne12 * ne13);
  2139. }
  2140. }
  2141. static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2142. #ifdef GGML_VULKAN_DEBUG
  2143. std::cerr << "ggml_vk_mul_mat_vec_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  2144. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  2145. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "),)" << std::endl;
  2146. #endif
  2147. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  2148. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  2149. const uint64_t ne00 = src0->ne[0];
  2150. const uint64_t ne01 = src0->ne[1];
  2151. const uint64_t ne02 = src0->ne[2];
  2152. const uint64_t ne03 = src0->ne[3];
  2153. const uint64_t ne10 = src1->ne[0];
  2154. const uint64_t ne11 = src1->ne[1];
  2155. const uint64_t ne12 = src1->ne[2];
  2156. const uint64_t ne13 = src1->ne[3];
  2157. GGML_ASSERT(ne11 == 1);
  2158. const uint64_t nb2 = dst->nb[2];
  2159. const uint64_t nb3 = dst->nb[3];
  2160. const uint64_t r2 = ne12 / ne02;
  2161. const uint64_t r3 = ne13 / ne03;
  2162. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2163. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2164. ggml_tensor_extra_gpu * extra_src1 = (ggml_tensor_extra_gpu *) src1->extra;
  2165. vk_buffer d_Qx;
  2166. size_t qx_buf_offset = 0;
  2167. vk_buffer d_Qy;
  2168. size_t qy_buf_offset = 0;
  2169. bool src0_uma = false;
  2170. bool src1_uma = false;
  2171. if (ctx->device->uma) {
  2172. ggml_vk_host_get(ctx, src0->data, d_Qx, qx_buf_offset);
  2173. ggml_vk_host_get(ctx, src1->data, d_Qy, qy_buf_offset);
  2174. src0_uma = d_Qx != nullptr;
  2175. src1_uma = d_Qy != nullptr;
  2176. }
  2177. const bool load_x = src0->backend != GGML_BACKEND_TYPE_GPU && !src0_uma;
  2178. const bool load_y = src1->backend != GGML_BACKEND_TYPE_GPU && !src1_uma;
  2179. const bool x_non_contig = !load_x && !ggml_vk_dim01_contiguous(src0);
  2180. const bool y_non_contig = !load_y && !ggml_vk_dim01_contiguous(src1);
  2181. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  2182. const bool qx_needs_dequant = x_non_contig;
  2183. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  2184. const uint64_t x_ne = ne01 * ne00;
  2185. const uint64_t y_ne = ne11 * ne10;
  2186. const uint64_t d_ne = ne11 * ne01;
  2187. 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);
  2188. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  2189. 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;
  2190. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  2191. const uint64_t d_sz = sizeof(float) * d_ne;
  2192. vk_buffer d_D = extra->buffer_gpu.lock();
  2193. const uint64_t d_buf_offset = extra->offset;
  2194. GGML_ASSERT(d_D != nullptr);
  2195. vk_buffer d_X;
  2196. uint64_t x_buf_offset = 0;
  2197. vk_buffer d_Y;
  2198. uint64_t y_buf_offset = 0;
  2199. if (load_x) {
  2200. d_Qx = ctx->prealloc_qx;
  2201. } else if(!src1_uma) {
  2202. d_Qx = extra_src0->buffer_gpu.lock();
  2203. qx_buf_offset = extra_src0->offset;
  2204. GGML_ASSERT(d_Qx != nullptr);
  2205. }
  2206. if (load_y) {
  2207. d_Qy = ctx->prealloc_qy;
  2208. } else if(!src1_uma) {
  2209. d_Qy = extra_src1->buffer_gpu.lock();
  2210. qy_buf_offset = extra_src1->offset;
  2211. GGML_ASSERT(d_Qy != nullptr);
  2212. }
  2213. if (qx_needs_dequant) {
  2214. d_X = ctx->prealloc_x;
  2215. } else {
  2216. d_X = d_Qx;
  2217. x_buf_offset = qx_buf_offset;
  2218. GGML_ASSERT(qx_sz == x_sz);
  2219. }
  2220. if (qy_needs_dequant) {
  2221. d_Y = ctx->prealloc_y;
  2222. } else {
  2223. d_Y = d_Qy;
  2224. y_buf_offset = qy_buf_offset;
  2225. GGML_ASSERT(qy_sz == y_sz);
  2226. }
  2227. vk_pipeline to_fp16_vk_0 = nullptr;
  2228. vk_pipeline to_fp16_vk_1 = nullptr;
  2229. if (x_non_contig) {
  2230. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0->type, src0->type);
  2231. }
  2232. if (y_non_contig) {
  2233. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1->type, src1->type);
  2234. } else {
  2235. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  2236. }
  2237. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type);
  2238. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  2239. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  2240. GGML_ASSERT(dmmv != nullptr);
  2241. // Allocate descriptor sets
  2242. if (qx_needs_dequant) {
  2243. ggml_pipeline_allocate_descriptor_sets(ctx, to_fp16_vk_0, 1);
  2244. }
  2245. if (qy_needs_dequant) {
  2246. ggml_pipeline_allocate_descriptor_sets(ctx, to_fp16_vk_1, y_non_contig ? 1 : ne12 * ne13);
  2247. }
  2248. ggml_pipeline_allocate_descriptor_sets(ctx, dmmv, ne12 * ne13);
  2249. if (x_non_contig) {
  2250. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  2251. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  2252. } else if (load_x) {
  2253. // copy data to device
  2254. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qx, 0, src0, 0, 0, ggml_nrows(src0));
  2255. }
  2256. if (y_non_contig) {
  2257. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  2258. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  2259. } else if (load_y) {
  2260. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qy, 0, src1, 0, 0, ggml_nrows(src1));
  2261. }
  2262. for (uint64_t i13 = 0; i13 < ne13; i13++) {
  2263. const uint64_t i03 = i13 / r3;
  2264. for (uint64_t i12 = 0; i12 < ne12; i12++) {
  2265. const uint64_t i02 = i12 / r2;
  2266. const uint64_t it_idx0 = (i03 * ne02 + i02);
  2267. const uint64_t it_idx1 = (i13 * ne12 + i12);
  2268. const uint64_t x_offset = x_buf_offset + x_sz * it_idx0;
  2269. const uint64_t qy_offset = qy_buf_offset + qy_sz * it_idx1;
  2270. const uint64_t y_offset = y_buf_offset + y_sz * it_idx1;
  2271. const uint64_t d_offset = d_buf_offset + d_sz * it_idx1;
  2272. const uint64_t y_buffer_offset = (y_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  2273. const uint64_t y_shader_offset = y_offset - y_buffer_offset;
  2274. const uint64_t d_buffer_offset = (d_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  2275. const uint64_t d_shader_offset = d_offset - d_buffer_offset;
  2276. if (!y_non_contig && qy_needs_dequant) {
  2277. const std::vector<uint32_t> pc = { (uint32_t)ne11, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(y_ne / 32) };
  2278. ggml_vk_sync_buffers(subctx);
  2279. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_1, { { d_Qy, qy_offset, qy_sz }, { d_Y, y_offset, y_sz } }, pc.size() * sizeof(uint32_t), pc.data(), { (uint32_t)y_ne, 1, 1});
  2280. }
  2281. // compute
  2282. const std::array<uint32_t, 3> pc = { (uint32_t)ne00, (uint32_t)(y_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type))};
  2283. ggml_vk_sync_buffers(subctx);
  2284. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv, { { d_X, x_offset, x_sz }, { d_Y, y_buffer_offset, y_sz + y_shader_offset }, { d_D, d_buffer_offset, d_sz + d_shader_offset } }, 3 * sizeof(int), &pc, { (uint32_t)ne01, 1, 1});
  2285. if (dst->backend == GGML_BACKEND_TYPE_CPU) {
  2286. // copy dst to host
  2287. float * d = (float *) ((char *) dst->data + i12*nb2 + i13*nb3);
  2288. ggml_vk_sync_buffers(subctx);
  2289. ggml_vk_buffer_read_async(ctx, subctx, d_D, d_offset, d, sizeof(float) * d_ne);
  2290. }
  2291. }
  2292. }
  2293. }
  2294. static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2295. #ifdef GGML_VULKAN_DEBUG
  2296. std::cerr << "ggml_vk_mul_mat_p021_f16_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  2297. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  2298. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "),)" << std::endl;
  2299. #endif
  2300. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  2301. GGML_ASSERT(src0->backend == GGML_BACKEND_TYPE_GPU);
  2302. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  2303. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  2304. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  2305. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  2306. const uint64_t ne00 = src0->ne[0];
  2307. const uint64_t ne01 = src0->ne[1];
  2308. const uint64_t ne02 = src0->ne[2];
  2309. // const uint64_t ne03 = src0->ne[3];
  2310. const uint64_t ne10 = src1->ne[0];
  2311. const uint64_t ne11 = src1->ne[1];
  2312. const uint64_t ne12 = src1->ne[2];
  2313. // const uint64_t ne13 = src1->ne[3];
  2314. GGML_ASSERT(ne11 == 1);
  2315. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2316. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2317. ggml_tensor_extra_gpu * extra_src1 = (ggml_tensor_extra_gpu *) src1->extra;
  2318. vk_buffer d_Qy;
  2319. size_t qy_buf_offset = 0;
  2320. bool src1_uma = false;
  2321. if (ctx->device->uma) {
  2322. ggml_vk_host_get(ctx, src1->data, d_Qy, qy_buf_offset);
  2323. src1_uma = d_Qy != nullptr;
  2324. }
  2325. const bool load_y = src1->backend != GGML_BACKEND_TYPE_GPU && !src1_uma;
  2326. const uint64_t x_ne = ne00 * ne01 * ne02;
  2327. const uint64_t y_ne = ne10 * ne11 * ne12;
  2328. const uint64_t d_ne = ne01 * ne11 * ne12;
  2329. 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);
  2330. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  2331. const uint64_t d_sz = sizeof(float) * d_ne;
  2332. vk_buffer d_D = extra->buffer_gpu.lock();
  2333. const uint64_t d_buf_offset = extra->offset;
  2334. GGML_ASSERT(d_D != nullptr);
  2335. vk_buffer d_Qx = extra_src0->buffer_gpu.lock();
  2336. const uint64_t qx_buf_offset = extra_src0->offset;
  2337. GGML_ASSERT(d_Qx != nullptr);
  2338. if (load_y) {
  2339. d_Qy = ctx->prealloc_qy;
  2340. } else if (!src1_uma) {
  2341. d_Qy = extra_src1->buffer_gpu.lock();
  2342. qy_buf_offset = extra_src1->offset;
  2343. GGML_ASSERT(d_Qx != nullptr);
  2344. }
  2345. // Allocate descriptor sets
  2346. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, 1);
  2347. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  2348. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  2349. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  2350. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  2351. if (load_y) {
  2352. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qy, qy_buf_offset, src1, 0, 0, ggml_nrows(src1));
  2353. }
  2354. // compute
  2355. const std::array<uint32_t, 6> pc = { (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)) };
  2356. ggml_vk_sync_buffers(subctx);
  2357. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, { { d_Qx, qx_buf_offset, qx_sz }, { d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, { d_D, d_buffer_offset, d_sz + d_shader_offset } }, 6 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  2358. if (dst->backend == GGML_BACKEND_TYPE_CPU) {
  2359. // copy dst to host
  2360. float * d = (float *) dst->data;
  2361. ggml_vk_sync_buffers(subctx);
  2362. ggml_vk_buffer_read_async(ctx, subctx, d_D, d_buf_offset, d, sizeof(float) * d_ne);
  2363. }
  2364. }
  2365. static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2366. #ifdef GGML_VULKAN_DEBUG
  2367. std::cerr << "ggml_vk_mul_mat_nc_f16_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  2368. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  2369. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "),)" << std::endl;
  2370. #endif
  2371. GGML_ASSERT(!ggml_is_transposed(src0));
  2372. GGML_ASSERT(!ggml_is_transposed(src1));
  2373. GGML_ASSERT(!ggml_is_permuted(src0));
  2374. GGML_ASSERT(src0->backend == GGML_BACKEND_TYPE_GPU);
  2375. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  2376. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  2377. const uint64_t ne00 = src0->ne[0];
  2378. const uint64_t ne01 = src0->ne[1];
  2379. const uint64_t ne02 = src0->ne[2];
  2380. // const uint64_t ne03 = src0->ne[3];
  2381. const uint64_t nb01 = src0->nb[1];
  2382. const uint64_t nb02 = src0->nb[2];
  2383. // const uint64_t ne10 = src1->ne[0];
  2384. const uint64_t ne11 = src1->ne[1];
  2385. const uint64_t ne12 = src1->ne[2];
  2386. // const uint64_t ne13 = src1->ne[3];
  2387. GGML_ASSERT(ne11 == 1);
  2388. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2389. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2390. ggml_tensor_extra_gpu * extra_src1 = (ggml_tensor_extra_gpu *) src1->extra;
  2391. vk_buffer d_Qy = nullptr;
  2392. size_t qy_buf_offset = 0;
  2393. bool src1_uma = false;
  2394. if (ctx->device->uma) {
  2395. ggml_vk_host_get(ctx, src1->data, d_Qy, qy_buf_offset);
  2396. src1_uma = d_Qy != nullptr;
  2397. }
  2398. const bool load_y = src1->backend != GGML_BACKEND_TYPE_GPU && !src1_uma;
  2399. const uint64_t d_ne = ne01 * ne11 * ne12;
  2400. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  2401. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  2402. const uint64_t qx_sz = ggml_nbytes(src0);
  2403. const uint64_t qy_sz = ggml_nbytes(src1);
  2404. const uint64_t d_sz = sizeof(float) * d_ne;
  2405. vk_buffer d_D = extra->buffer_gpu.lock();
  2406. const uint64_t d_buf_offset = extra->offset;
  2407. GGML_ASSERT(d_D != nullptr);
  2408. vk_buffer d_Qx = extra_src0->buffer_gpu.lock();
  2409. const uint64_t qx_buf_offset = extra_src0->offset;
  2410. GGML_ASSERT(d_Qx != nullptr);
  2411. if (load_y) {
  2412. d_Qy = ctx->prealloc_qy;
  2413. } else {
  2414. d_Qy = extra_src1->buffer_gpu.lock();
  2415. qy_buf_offset = extra_src1->offset;
  2416. GGML_ASSERT(d_Qx != nullptr);
  2417. }
  2418. // Allocate descriptor sets
  2419. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  2420. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  2421. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  2422. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  2423. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  2424. if (load_y) {
  2425. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Qy, qy_buf_offset, src1, 0, 0, ggml_nrows(src1));
  2426. }
  2427. // compute
  2428. const std::array<uint32_t, 7> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, (uint32_t)(ne12 / ne02), (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)) };
  2429. ggml_vk_sync_buffers(subctx);
  2430. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, { { d_Qx, qx_buf_offset, qx_sz }, { d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, { d_D, d_buffer_offset, d_sz + d_shader_offset } }, 7 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  2431. if (dst->backend == GGML_BACKEND_TYPE_CPU) {
  2432. // copy dst to host
  2433. float * d = (float *) dst->data;
  2434. ggml_vk_sync_buffers(subctx);
  2435. ggml_vk_buffer_read_async(ctx, subctx, d_D, d_buf_offset, d, sizeof(float) * d_ne);
  2436. }
  2437. }
  2438. static bool ggml_vk_can_mul_mat(const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst) {
  2439. const uint64_t ne10 = src1->ne[0];
  2440. const uint64_t ne0 = dst->ne[0];
  2441. const uint64_t ne1 = dst->ne[1];
  2442. // TODO: find the optimal values for these
  2443. return (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) &&
  2444. (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || ggml_is_quantized(src1->type)) &&
  2445. dst->type == GGML_TYPE_F32 &&
  2446. ((ne0 >= 32 && ne1 >= 32 && ne10 >= 32) || src0->backend == GGML_BACKEND_TYPE_GPU);
  2447. }
  2448. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context * subctx, const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  2449. #ifdef GGML_VULKAN_DEBUG
  2450. std::cerr << "ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")" << std::endl;
  2451. #endif
  2452. if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && src1->ne[1] == 1) {
  2453. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst);
  2454. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && src1->ne[1] == 1) {
  2455. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst);
  2456. } else if (src1->ne[1] == 1 && (src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  2457. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst);
  2458. } else {
  2459. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst);
  2460. }
  2461. }
  2462. // static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context * subctx, const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) {
  2463. //
  2464. // }
  2465. static void ggml_vk_op_repeat(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2466. // guaranteed to be an integer due to the check in ggml_can_repeat
  2467. const uint64_t ne0 = dst->ne[0];
  2468. const uint64_t ne1 = dst->ne[1];
  2469. const uint64_t ne2 = dst->ne[2];
  2470. const uint64_t ne3 = dst->ne[3];
  2471. const uint64_t ne00 = src0->ne[0];
  2472. const uint64_t ne01 = src0->ne[1];
  2473. const uint64_t ne02 = src0->ne[2];
  2474. const uint64_t ne03 = src0->ne[3];
  2475. const uint64_t nb0 = dst->nb[0];
  2476. const uint64_t nb1 = dst->nb[1];
  2477. const uint64_t nb2 = dst->nb[2];
  2478. const uint64_t nb3 = dst->nb[3];
  2479. const uint64_t nb00 = src0->nb[0];
  2480. const uint64_t nb01 = src0->nb[1];
  2481. const uint64_t nb02 = src0->nb[2];
  2482. const uint64_t nb03 = src0->nb[3];
  2483. const uint64_t nr0 = ne0/ne00;
  2484. const uint64_t nr1 = ne1/ne01;
  2485. const uint64_t nr2 = ne2/ne02;
  2486. const uint64_t nr3 = ne3/ne03;
  2487. // TODO: support for transposed / permuted tensors
  2488. GGML_ASSERT(nb0 == sizeof(float));
  2489. GGML_ASSERT(nb00 == sizeof(float));
  2490. GGML_ASSERT(src0->backend == GGML_BACKEND_TYPE_GPU);
  2491. GGML_ASSERT(dst->backend == GGML_BACKEND_TYPE_GPU);
  2492. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2493. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2494. const vk_buffer src_buf = extra_src0->buffer_gpu.lock();
  2495. const uint64_t src_offset = extra_src0->offset;
  2496. vk_buffer dst_buf = extra->buffer_gpu.lock();
  2497. const uint64_t dst_offset = extra->offset;
  2498. std::vector<vk::BufferCopy> copies;
  2499. for (uint64_t i3 = 0; i3 < nr3; i3++) {
  2500. for (uint64_t k3 = 0; k3 < ne03; k3++) {
  2501. for (uint64_t i2 = 0; i2 < nr2; i2++) {
  2502. for (uint64_t k2 = 0; k2 < ne02; k2++) {
  2503. for (uint64_t i1 = 0; i1 < nr1; i1++) {
  2504. for (uint64_t k1 = 0; k1 < ne01; k1++) {
  2505. for (uint64_t i0 = 0; i0 < nr0; i0++) {
  2506. copies.push_back({
  2507. src_offset + (i3*ne03 + k3)*nb3 + (i2*ne02 + k2)*nb2 + (i1*ne01 + k1)*nb1 + (i0*ne00)*nb0,
  2508. dst_offset + ( k3)*nb03 + ( k2)*nb02 + ( k1)*nb01,
  2509. ne00*nb0,
  2510. });
  2511. }
  2512. }
  2513. }
  2514. }
  2515. }
  2516. }
  2517. }
  2518. ggml_vk_sync_buffers(subctx);
  2519. subctx->s->buffer.copyBuffer(src_buf->buffer, dst_buf->buffer, copies);
  2520. GGML_UNUSED(ctx);
  2521. GGML_UNUSED(src1);
  2522. }
  2523. static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, ggml_op op) {
  2524. switch (op) {
  2525. case GGML_OP_ADD:
  2526. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2527. return ctx->device->pipeline_add_f32;
  2528. }
  2529. return nullptr;
  2530. case GGML_OP_GET_ROWS:
  2531. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  2532. if (dst->type == GGML_TYPE_F16) {
  2533. return ctx->device->pipeline_get_rows[src0->type];
  2534. }
  2535. if (dst->type == GGML_TYPE_F32) {
  2536. return ctx->device->pipeline_get_rows_f32[src0->type];
  2537. }
  2538. return nullptr;
  2539. case GGML_OP_MUL:
  2540. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2541. return ctx->device->pipeline_mul_f32;
  2542. }
  2543. return nullptr;
  2544. case GGML_OP_SCALE:
  2545. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2546. return ctx->device->pipeline_scale_f32;
  2547. }
  2548. return nullptr;
  2549. case GGML_OP_SQR:
  2550. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2551. return ctx->device->pipeline_sqr_f32;
  2552. }
  2553. return nullptr;
  2554. case GGML_OP_CLAMP:
  2555. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2556. return ctx->device->pipeline_clamp_f32;
  2557. }
  2558. return nullptr;
  2559. case GGML_OP_CPY:
  2560. case GGML_OP_CONT:
  2561. case GGML_OP_DUP:
  2562. return ggml_vk_get_cpy_pipeline(ctx, src0->type, dst->type);
  2563. case GGML_OP_NORM:
  2564. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2565. return ctx->device->pipeline_norm_f32;
  2566. }
  2567. return nullptr;
  2568. case GGML_OP_RMS_NORM:
  2569. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2570. return ctx->device->pipeline_rms_norm_f32;
  2571. }
  2572. return nullptr;
  2573. case GGML_OP_UNARY:
  2574. switch (ggml_get_unary_op(dst)) {
  2575. case GGML_UNARY_OP_SILU:
  2576. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2577. return ctx->device->pipeline_silu_f32;
  2578. }
  2579. break;
  2580. case GGML_UNARY_OP_GELU:
  2581. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2582. return ctx->device->pipeline_gelu_f32;
  2583. }
  2584. break;
  2585. case GGML_UNARY_OP_RELU:
  2586. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2587. return ctx->device->pipeline_relu_f32;
  2588. }
  2589. break;
  2590. default:
  2591. break;
  2592. }
  2593. return nullptr;
  2594. case GGML_OP_DIAG_MASK_INF:
  2595. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2596. return ctx->device->pipeline_diag_mask_inf_f32;
  2597. }
  2598. return nullptr;
  2599. case GGML_OP_SOFT_MAX:
  2600. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && (src2 == nullptr || src2->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  2601. return ctx->device->pipeline_soft_max_f32;
  2602. }
  2603. return nullptr;
  2604. case GGML_OP_ROPE:
  2605. {
  2606. const int mode = ((const int32_t *) dst->op_params)[2];
  2607. const bool is_neox = mode & 2;
  2608. const bool is_glm = mode & 4;
  2609. if (is_glm) {
  2610. return nullptr;
  2611. }
  2612. if (is_neox) {
  2613. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2614. return ctx->device->pipeline_rope_neox_f32;
  2615. }
  2616. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  2617. return ctx->device->pipeline_rope_neox_f16;
  2618. }
  2619. } else {
  2620. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  2621. return ctx->device->pipeline_rope_f32;
  2622. }
  2623. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  2624. return ctx->device->pipeline_rope_f16;
  2625. }
  2626. }
  2627. return nullptr;
  2628. }
  2629. case GGML_OP_ARGSORT:
  2630. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  2631. return ctx->device->pipeline_argsort_f32;
  2632. }
  2633. return nullptr;
  2634. default:
  2635. return nullptr;
  2636. }
  2637. }
  2638. static ggml_vk_func_t ggml_vk_op_get_func(ggml_op op) {
  2639. switch(op) {
  2640. case GGML_OP_REPEAT:
  2641. return ggml_vk_op_repeat;
  2642. default:
  2643. return nullptr;
  2644. }
  2645. }
  2646. template<typename PC>
  2647. static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, ggml_op op, const PC&& pc) {
  2648. #ifdef GGML_VULKAN_DEBUG
  2649. std::cerr << "ggml_vk_op_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", backend=" << src0->backend << ", 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];
  2650. if (src1 != nullptr) {
  2651. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", backend=" << src1->backend << ", 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];
  2652. }
  2653. if (src2 != nullptr) {
  2654. std::cerr << "), (" << src2 << ", name=" << src2->name << ", type=" << src2->type << ", backend=" << src2->backend << ", 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];
  2655. }
  2656. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", backend=" << dst->backend << ", 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] << "), " << ggml_op_name(op) << ")" << std::endl;
  2657. #endif
  2658. GGML_ASSERT(!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type))); // NOLINT
  2659. GGML_ASSERT(op == GGML_OP_CPY || ggml_vk_dim01_contiguous(src0)); // NOLINT
  2660. GGML_ASSERT(dst->extra != nullptr);
  2661. const uint64_t ne00 = src0->ne[0];
  2662. const uint64_t ne01 = src0->ne[1];
  2663. const uint64_t ne02 = src0->ne[2];
  2664. const uint64_t ne03 = src0->ne[3];
  2665. const uint64_t ne0 = ne00 * ne01;
  2666. const bool use_src1 = src1 != nullptr;
  2667. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  2668. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  2669. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  2670. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  2671. const uint64_t ne1 = ne10 * ne11;
  2672. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  2673. const uint64_t nb2 = dst->nb[2];
  2674. const uint64_t nb3 = dst->nb[3];
  2675. const bool use_src2 = src2 != nullptr;
  2676. const uint64_t ne2 = use_src2 ? src2->ne[0] * src2->ne[1] : 0;
  2677. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  2678. ggml_vk_func_t op_func;
  2679. if (pipeline == nullptr) {
  2680. op_func = ggml_vk_op_get_func(op);
  2681. if (op_func == nullptr) {
  2682. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  2683. if (src1 != nullptr) {
  2684. std::cerr << " and " << ggml_type_name(src1->type);
  2685. }
  2686. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  2687. GGML_ASSERT(false);
  2688. }
  2689. op_func(ctx, subctx, src0, src1, dst);
  2690. return;
  2691. }
  2692. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2693. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  2694. ggml_tensor_extra_gpu * extra_src1 = use_src1 ? (ggml_tensor_extra_gpu *) src1->extra : nullptr;
  2695. ggml_tensor_extra_gpu * extra_src2 = use_src2 ? (ggml_tensor_extra_gpu *) src2->extra : nullptr;
  2696. vk_buffer d_X = nullptr;
  2697. size_t x_buf_offset = 0;
  2698. vk_buffer d_Y = nullptr;
  2699. size_t y_buf_offset = 0;
  2700. vk_buffer d_Z = nullptr;
  2701. size_t z_buf_offset = 0;
  2702. bool src0_uma = false;
  2703. bool src1_uma = false;
  2704. bool src2_uma = false;
  2705. if (ctx->device->uma) {
  2706. ggml_vk_host_get(ctx, src0->data, d_X, x_buf_offset);
  2707. src0_uma = d_X != nullptr;
  2708. if (use_src1) {
  2709. ggml_vk_host_get(ctx, src1->data, d_Y, y_buf_offset);
  2710. src1_uma = d_Y != nullptr;
  2711. }
  2712. if (use_src2) {
  2713. ggml_vk_host_get(ctx, src1->data, d_Z, z_buf_offset);
  2714. src2_uma = d_Z != nullptr;
  2715. }
  2716. }
  2717. const bool transfer_src0 = src0->backend != GGML_BACKEND_TYPE_GPU && !src0_uma;
  2718. const bool transfer_src1 = use_src1 && src1->backend != GGML_BACKEND_TYPE_GPU && !src1_uma;
  2719. const bool transfer_src2 = use_src2 && src2->backend != GGML_BACKEND_TYPE_GPU && !src2_uma;
  2720. uint64_t x_sz = ggml_vk_align_size(ggml_type_size(src0->type) * ne0, ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  2721. uint64_t y_sz = use_src1 ? ggml_vk_align_size(ggml_type_size(src1->type) * ne1, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : 0;
  2722. uint64_t z_sz = use_src2 ? ggml_vk_align_size(ggml_type_size(src2->type) * ne2, ctx->device->properties.limits.minStorageBufferOffsetAlignment) : 0;
  2723. uint64_t d_sz = ggml_type_size(dst->type) * ne0;
  2724. vk_buffer d_D = extra->buffer_gpu.lock();
  2725. // Workaround for tiny tensor inputs on ROPE
  2726. if (use_src1 && src1->backend == GGML_BACKEND_TYPE_GPU && y_sz > d_D->size) {
  2727. y_sz = VK_WHOLE_SIZE;
  2728. }
  2729. GGML_ASSERT(d_D != nullptr);
  2730. uint64_t d_buf_offset = (extra->offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  2731. GGML_ASSERT(d_buf_offset == extra->offset || op == GGML_OP_CPY); // NOLINT
  2732. if (transfer_src0) {
  2733. d_X = ctx->prealloc_qx;
  2734. } else if(!src0_uma) {
  2735. d_X = extra_src0->buffer_gpu.lock();
  2736. x_buf_offset = extra_src0->offset;
  2737. GGML_ASSERT(d_X != nullptr);
  2738. }
  2739. if (transfer_src1) {
  2740. d_Y = ctx->prealloc_qy;
  2741. } else if (use_src1 && !src1_uma) {
  2742. d_Y = extra_src1->buffer_gpu.lock();
  2743. y_buf_offset = extra_src1->offset;
  2744. GGML_ASSERT(d_Y != nullptr);
  2745. }
  2746. GGML_ASSERT(!transfer_src2);
  2747. if (use_src2 && !src2_uma) {
  2748. d_Z = extra_src2->buffer_gpu.lock();
  2749. z_buf_offset = extra_src2->offset;
  2750. GGML_ASSERT(d_Z != nullptr);
  2751. }
  2752. if (op == GGML_OP_CPY) {
  2753. GGML_ASSERT(!transfer_src0);
  2754. GGML_ASSERT(!transfer_src1);
  2755. x_sz = ggml_nbytes(src0);
  2756. d_sz = ggml_nbytes(dst);
  2757. if (extra_src0->offset + x_sz >= d_X->size) {
  2758. x_sz = VK_WHOLE_SIZE;
  2759. }
  2760. if (extra->offset + d_sz >= d_D->size) {
  2761. d_sz = VK_WHOLE_SIZE;
  2762. }
  2763. }
  2764. std::array<uint32_t, 3> elements;
  2765. // copy src0 to device
  2766. if (transfer_src0) {
  2767. ggml_vk_h2d_tensor_2d(ctx, subctx, d_X, 0, src0, 0, 0, ggml_nrows(src0));
  2768. ctx->staging_offset = x_sz * ne02 * ne03;
  2769. }
  2770. if (transfer_src1) {
  2771. ggml_vk_h2d_tensor_2d(ctx, subctx, d_Y, 0, src1, 0, 0, ggml_nrows(src1));
  2772. }
  2773. // Single call if dimension 2 is contiguous
  2774. if (op == GGML_OP_CPY || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1)))) {
  2775. ggml_pipeline_allocate_descriptor_sets(ctx, pipeline, 1);
  2776. switch (dst->op) {
  2777. case GGML_OP_NORM:
  2778. case GGML_OP_RMS_NORM:
  2779. case GGML_OP_SOFT_MAX:
  2780. elements = { (uint32_t)ggml_nrows(src0), 1, 1 };
  2781. break;
  2782. case GGML_OP_DIAG_MASK_INF:
  2783. case GGML_OP_ROPE:
  2784. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  2785. break;
  2786. default:
  2787. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  2788. break;
  2789. }
  2790. if (op != GGML_OP_CPY) {
  2791. if (x_sz != VK_WHOLE_SIZE) {
  2792. x_sz *= ne02 * ne03;
  2793. }
  2794. if (y_sz != VK_WHOLE_SIZE) {
  2795. y_sz *= ne12 * ne13;
  2796. }
  2797. if (d_sz != VK_WHOLE_SIZE) {
  2798. d_sz *= ne02 * ne03;
  2799. }
  2800. }
  2801. if (op == GGML_OP_SOFT_MAX) {
  2802. // Empty src1 and src2 are possible on soft_max, but the shader needs buffers
  2803. vk_subbuffer subbuf_y;
  2804. if (use_src1) {
  2805. subbuf_y = { d_Y, y_buf_offset, y_sz };
  2806. } else {
  2807. subbuf_y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  2808. }
  2809. vk_subbuffer subbuf_z;
  2810. if (use_src2) {
  2811. subbuf_z = { d_Z, z_buf_offset, z_sz };
  2812. } else {
  2813. subbuf_z = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  2814. }
  2815. ggml_vk_sync_buffers(subctx);
  2816. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { { d_X, x_buf_offset, x_sz }, subbuf_y, subbuf_z, { d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  2817. } else if (use_src1) {
  2818. ggml_vk_sync_buffers(subctx);
  2819. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz }, { d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  2820. } else {
  2821. ggml_vk_sync_buffers(subctx);
  2822. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { { d_X, x_buf_offset, x_sz }, { d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  2823. }
  2824. if (dst->backend == GGML_BACKEND_TYPE_CPU && op == GGML_OP_CPY) {
  2825. ggml_vk_d2h_tensor_2d(ctx, subctx, d_D, 0, dst);
  2826. } else if(dst->backend == GGML_BACKEND_TYPE_CPU) {
  2827. // copy dst to host
  2828. float * d = (float *) dst->data;
  2829. ggml_vk_buffer_read_async(ctx, subctx, d_D, 0, d, d_sz);
  2830. }
  2831. } else {
  2832. GGML_ASSERT(op != GGML_OP_SOFT_MAX);
  2833. ggml_pipeline_allocate_descriptor_sets(ctx, pipeline, ne02 * ne03);
  2834. switch (dst->op) {
  2835. case GGML_OP_NORM:
  2836. case GGML_OP_RMS_NORM:
  2837. case GGML_OP_SOFT_MAX:
  2838. elements = { (uint32_t)ne01, 1, 1 };
  2839. break;
  2840. case GGML_OP_DIAG_MASK_INF:
  2841. case GGML_OP_ROPE:
  2842. elements = { (uint32_t)ne01, (uint32_t)ne00, 1 };
  2843. break;
  2844. default:
  2845. elements = { (uint32_t)ne0, 1, 1 };
  2846. break;
  2847. }
  2848. for (uint64_t i03 = 0; i03 < ne03; i03++) {
  2849. for (uint64_t i02 = 0; i02 < ne02; i02++) {
  2850. const uint32_t it_idx0 = (i03 * ne02 + i02);
  2851. const uint32_t it_idx1 = use_src1 ? ((i03 % ne13) * ne12 + (i02 % ne12)) : 0;
  2852. const uint32_t x_offset = x_sz * it_idx0;
  2853. const uint32_t y_offset = y_sz * it_idx1;
  2854. const uint32_t d_offset = d_sz * it_idx0;
  2855. if (use_src1) {
  2856. ggml_vk_sync_buffers(subctx);
  2857. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { { d_X, x_buf_offset + x_offset, x_sz }, { d_Y, y_buf_offset + y_offset, y_sz }, { d_D, d_buf_offset + d_offset, d_sz } }, sizeof(PC), &pc, elements);
  2858. } else {
  2859. ggml_vk_sync_buffers(subctx);
  2860. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { { d_X, x_buf_offset + x_offset, x_sz }, { d_D, d_buf_offset + d_offset, d_sz } }, sizeof(PC), &pc, elements);
  2861. }
  2862. if (dst->backend == GGML_BACKEND_TYPE_CPU) {
  2863. // copy dst to host
  2864. ggml_vk_buffer_read_async(ctx, subctx, d_D, d_buf_offset + d_offset, (char *) dst->data + i02*nb2 + i03*nb3, d_sz);
  2865. }
  2866. }
  2867. }
  2868. }
  2869. }
  2870. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2871. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_REPEAT, { (uint32_t)ggml_nelements(src0), (uint32_t)ggml_nelements(src1), 0.0f, 0.0f });
  2872. }
  2873. 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) {
  2874. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GET_ROWS, { (uint32_t)ggml_nelements(src0), (uint32_t)ggml_nelements(src1), 0.0f, 0.0f });
  2875. }
  2876. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2877. const uint32_t src0_type_size = ggml_type_size(src0->type);
  2878. const uint32_t src1_type_size = ggml_type_size(src1->type);
  2879. const uint32_t dst_type_size = ggml_type_size(dst->type);
  2880. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ADD, {
  2881. (uint32_t)ggml_nelements(src0),
  2882. (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,
  2883. (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,
  2884. (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,
  2885. 0,
  2886. 0.0f, 0.0f,
  2887. });
  2888. }
  2889. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2890. const uint32_t src0_type_size = ggml_type_size(src0->type);
  2891. const uint32_t src1_type_size = ggml_type_size(src1->type);
  2892. const uint32_t dst_type_size = ggml_type_size(dst->type);
  2893. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_MUL, {
  2894. (uint32_t)ggml_nelements(src0),
  2895. (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,
  2896. (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,
  2897. (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,
  2898. 0,
  2899. 0.0f, 0.0f,
  2900. });
  2901. }
  2902. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2903. float * op_params = (float *)dst->op_params;
  2904. const uint32_t src0_type_size = ggml_type_size(src0->type);
  2905. const uint32_t dst_type_size = ggml_type_size(dst->type);
  2906. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SCALE, {
  2907. (uint32_t)ggml_nelements(src0),
  2908. (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,
  2909. (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,
  2910. 0,
  2911. op_params[0], 0.0f
  2912. });
  2913. }
  2914. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2915. const uint32_t src0_type_size = ggml_type_size(src0->type);
  2916. const uint32_t dst_type_size = ggml_type_size(dst->type);
  2917. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQR, {
  2918. (uint32_t)ggml_nelements(src0),
  2919. (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,
  2920. (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,
  2921. 0,
  2922. 0.0f, 0.0f,
  2923. });
  2924. }
  2925. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2926. float * op_params = (float *)dst->op_params;
  2927. const uint32_t src0_type_size = ggml_type_size(src0->type);
  2928. const uint32_t dst_type_size = ggml_type_size(dst->type);
  2929. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CLAMP, {
  2930. (uint32_t)ggml_nelements(src0),
  2931. (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,
  2932. (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,
  2933. 0,
  2934. op_params[0], op_params[1],
  2935. });
  2936. }
  2937. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2938. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) dst->extra;
  2939. const uint32_t src0_type_size = ggml_type_size(src0->type);
  2940. const uint32_t dst_type_size = ggml_type_size(dst->type);
  2941. const uint32_t d_offset = (extra->offset % ctx->device->properties.limits.minStorageBufferOffsetAlignment) / dst_type_size;
  2942. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CPY, {
  2943. (uint32_t)ggml_nelements(src0),
  2944. (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,
  2945. (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,
  2946. d_offset,
  2947. 0.0f, 0.0f,
  2948. });
  2949. }
  2950. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2951. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f });
  2952. }
  2953. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2954. float * op_params = (float *)dst->op_params;
  2955. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_RMS_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  2956. }
  2957. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2958. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  2959. }
  2960. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  2961. int32_t * op_params = (int32_t *)dst->op_params;
  2962. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] });
  2963. }
  2964. 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) {
  2965. float * op_params = (float *)dst->op_params;
  2966. float scale = op_params[0];
  2967. float max_bias = op_params[1];
  2968. const uint32_t ncols = (uint32_t)src0->ne[0];
  2969. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  2970. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  2971. const uint32_t n_head_kv = nrows_x/nrows_y;
  2972. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  2973. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  2974. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  2975. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_SOFT_MAX, {
  2976. ncols,
  2977. nrows_y,
  2978. src2 != nullptr ? (uint32_t)1 : (uint32_t)0,
  2979. scale, max_bias,
  2980. m0, m1,
  2981. n_head_log2,
  2982. });
  2983. }
  2984. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  2985. const int n_dims = ((int32_t *) dst->op_params)[1];
  2986. const int mode = ((int32_t *) dst->op_params)[2];
  2987. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  2988. const int n_orig_ctx = ((int32_t *) dst->op_params)[4];
  2989. const float freq_base = ((float *) dst->op_params)[5];
  2990. const float freq_scale = ((float *) dst->op_params)[6];
  2991. const float ext_factor = ((float *) dst->op_params)[7];
  2992. const float attn_factor = ((float *) dst->op_params)[8];
  2993. const float beta_fast = ((float *) dst->op_params)[9];
  2994. const float beta_slow = ((float *) dst->op_params)[10];
  2995. const bool is_neox = mode & 2;
  2996. const bool is_glm = mode & 4;
  2997. GGML_ASSERT(!is_glm);
  2998. float corr_dims[2];
  2999. ggml_rope_yarn_corr_dims(n_dims, n_orig_ctx, freq_base, beta_fast, beta_slow, corr_dims);
  3000. if (is_neox) {
  3001. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  3002. const float inv_ndims = -1.0f / n_dims;
  3003. ggml_vk_op_f32<vk_op_rope_neox_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ROPE, { (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1], freq_base, ext_factor, attn_factor, corr_dims[0], corr_dims[1], 0.0f, 0.0f, theta_scale, inv_ndims });
  3004. } else {
  3005. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ROPE, { (uint32_t)src0->ne[0], freq_scale, (uint32_t)src0->ne[1], freq_base, ext_factor, attn_factor, corr_dims[0], corr_dims[1], 0.0f, 0.0f });
  3006. }
  3007. }
  3008. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  3009. int32_t * op_params = (int32_t *)dst->op_params;
  3010. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGSORT, { (uint32_t)src0->ne[0], ((ggml_sort_order) op_params[0]) == GGML_SORT_ORDER_ASC });
  3011. }
  3012. static void ggml_vk_nop(ggml_backend_vk_context * ctx, vk_context * subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  3013. // If backend is CPU, data from src0 has to be copied off the device
  3014. if (dst->backend == GGML_BACKEND_TYPE_CPU) {
  3015. ggml_tensor_extra_gpu * extra_src0 = (ggml_tensor_extra_gpu *) src0->extra;
  3016. vk_buffer d_D = extra_src0->buffer_gpu.lock();
  3017. ggml_vk_sync_buffers(subctx);
  3018. ggml_vk_buffer_read_async(ctx, subctx, d_D, 0, dst->data, d_D->size);
  3019. }
  3020. }
  3021. #ifdef GGML_VULKAN_RUN_TESTS
  3022. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  3023. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  3024. return;
  3025. }
  3026. i0 = std::max(i0, 5);
  3027. i1 = std::max(i1, 5);
  3028. i2 = std::max(i2, 0);
  3029. fprintf(stderr, " ");
  3030. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  3031. fprintf(stderr, "%7d ", idx1);
  3032. }
  3033. fprintf(stderr, "\n");
  3034. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  3035. fprintf(stderr, "%7d: ", idx0);
  3036. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  3037. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  3038. float val;
  3039. if (type == GGML_TYPE_F32) {
  3040. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  3041. } else if (type == GGML_TYPE_F16) {
  3042. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  3043. }
  3044. fprintf(stderr, "% 7.2f ", val);
  3045. } else {
  3046. fprintf(stderr, " ");
  3047. }
  3048. }
  3049. fprintf(stderr, "\n");
  3050. }
  3051. }
  3052. template <typename X_TYPE, typename Y_TYPE>
  3053. 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) {
  3054. #ifdef GGML_VULKAN_DEBUG
  3055. std::cerr << "ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")" << std::endl;
  3056. #endif
  3057. const size_t x_ne = m * k * batch;
  3058. const size_t y_ne = k * n * batch;
  3059. const size_t d_ne = m * n * batch;
  3060. vk_pipeline p;
  3061. std::string shname;
  3062. if (shader_size == 0) {
  3063. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3064. p = ctx->device->pipeline_matmul_f32->a_s;
  3065. shname = "F32_ALIGNED_S";
  3066. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3067. p = ctx->device->pipeline_matmul_f16_f32->a_s;
  3068. shname = "F16_F32_ALIGNED_S";
  3069. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3070. p = ctx->device->pipeline_matmul_f16->a_s;
  3071. shname = "F16_ALIGNED_S";
  3072. } else {
  3073. GGML_ASSERT(false);
  3074. }
  3075. } else if (shader_size == 1) {
  3076. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3077. p = ctx->device->pipeline_matmul_f32->a_m;
  3078. shname = "F32_ALIGNED_M";
  3079. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3080. p = ctx->device->pipeline_matmul_f16_f32->a_m;
  3081. shname = "F16_F32_ALIGNED_M";
  3082. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3083. p = ctx->device->pipeline_matmul_f16->a_m;
  3084. shname = "F16_ALIGNED_M";
  3085. } else {
  3086. GGML_ASSERT(false);
  3087. }
  3088. } else if (shader_size == 2) {
  3089. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3090. p = ctx->device->pipeline_matmul_f32->a_l;
  3091. shname = "F32_ALIGNED_L";
  3092. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3093. p = ctx->device->pipeline_matmul_f16_f32->a_l;
  3094. shname = "F16_F32_ALIGNED_L";
  3095. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3096. p = ctx->device->pipeline_matmul_f16->a_l;
  3097. shname = "F16_ALIGNED_L";
  3098. } else {
  3099. GGML_ASSERT(false);
  3100. }
  3101. } else {
  3102. GGML_ASSERT(0);
  3103. }
  3104. const size_t kpad = ggml_vk_align_size(k, p->align);
  3105. if (k != kpad) {
  3106. if (shader_size == 0) {
  3107. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3108. p = ctx->device->pipeline_matmul_f32->s;
  3109. shname = "F32_S";
  3110. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3111. p = ctx->device->pipeline_matmul_f16_f32->s;
  3112. shname = "F16_F32_S";
  3113. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3114. p = ctx->device->pipeline_matmul_f16->s;
  3115. shname = "F16_S";
  3116. }
  3117. } else if (shader_size == 1) {
  3118. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3119. p = ctx->device->pipeline_matmul_f32->m;
  3120. shname = "F32_M";
  3121. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3122. p = ctx->device->pipeline_matmul_f16_f32->m;
  3123. shname = "F16_F32_M";
  3124. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3125. p = ctx->device->pipeline_matmul_f16->m;
  3126. shname = "F16_M";
  3127. }
  3128. } else if (shader_size == 2) {
  3129. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3130. p = ctx->device->pipeline_matmul_f32->l;
  3131. shname = "F32_L";
  3132. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  3133. p = ctx->device->pipeline_matmul_f16_f32->l;
  3134. shname = "F16_F32_L";
  3135. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3136. p = ctx->device->pipeline_matmul_f16->l;
  3137. shname = "F16_L";
  3138. }
  3139. }
  3140. }
  3141. ggml_pipeline_allocate_descriptor_sets(ctx, p, num_it);
  3142. if (split_k > 1) {
  3143. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  3144. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  3145. // Resize buffer
  3146. if (ctx->prealloc_split_k != nullptr) {
  3147. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  3148. }
  3149. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3150. }
  3151. }
  3152. vk_buffer d_X = ggml_vk_create_buffer_check(ctx, sizeof(X_TYPE) * x_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3153. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx, sizeof(Y_TYPE) * y_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3154. vk_buffer d_D = ggml_vk_create_buffer_check(ctx, sizeof(float) * d_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3155. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  3156. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  3157. float* d = (float *) malloc(sizeof(float) * d_ne);
  3158. for (size_t i = 0; i < x_ne; i++) {
  3159. if (std::is_same<float, X_TYPE>()) {
  3160. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  3161. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  3162. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  3163. } else {
  3164. GGML_ASSERT(false);
  3165. }
  3166. }
  3167. for (size_t i = 0; i < y_ne; i++) {
  3168. if (std::is_same<float, Y_TYPE>()) {
  3169. // y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  3170. y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  3171. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3172. // y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  3173. y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  3174. } else {
  3175. GGML_ASSERT(false);
  3176. }
  3177. }
  3178. ggml_vk_buffer_write(ctx, d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  3179. ggml_vk_buffer_write(ctx, d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  3180. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  3181. for (size_t i = 0; i < num_it; i++) {
  3182. ggml_vk_ctx_begin(ctx, subctx);
  3183. ggml_vk_matmul(ctx, subctx, p, ggml_vk_subbuffer(d_X), ggml_vk_subbuffer(d_Y), ggml_vk_subbuffer(d_D), ggml_vk_subbuffer(ctx->prealloc_split_k), m, n, k, k, k, m, split_k, batch, batch, batch, 1, 1, k*m, k*n, m*n);
  3184. ggml_vk_ctx_end(subctx);
  3185. }
  3186. auto begin = std::chrono::high_resolution_clock::now();
  3187. ggml_vk_submit(subctx, ctx->fence);
  3188. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  3189. ctx->device->device.resetFences({ ctx->fence });
  3190. auto end = std::chrono::high_resolution_clock::now();
  3191. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3192. // copy dst to host
  3193. ggml_vk_buffer_read(ctx, d_D, 0, d, sizeof(float) * d_ne);
  3194. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  3195. ggml_init_params iparams = {
  3196. /*.mem_size =*/ 1024*1024*1024,
  3197. /*.mem_buffer =*/ NULL,
  3198. /*.no_alloc =*/ true,
  3199. };
  3200. ggml_context * ggml_ctx = ggml_init(iparams);
  3201. ggml_type src0_type;
  3202. ggml_type src1_type;
  3203. if (std::is_same<float, X_TYPE>()) {
  3204. src0_type = GGML_TYPE_F32;
  3205. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  3206. src0_type = GGML_TYPE_F16;
  3207. } else {
  3208. GGML_ASSERT(false);
  3209. }
  3210. if (std::is_same<float, Y_TYPE>()) {
  3211. src1_type = GGML_TYPE_F32;
  3212. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  3213. src1_type = GGML_TYPE_F16;
  3214. } else {
  3215. GGML_ASSERT(false);
  3216. }
  3217. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  3218. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  3219. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  3220. src0_ggml->data = x;
  3221. src1_ggml->data = y;
  3222. tensor_ggml->data = d_chk;
  3223. ctx->disable = true;
  3224. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  3225. ggml_build_forward_expand(cgraph, tensor_ggml);
  3226. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  3227. ctx->disable = false;
  3228. ggml_free(ggml_ctx);
  3229. double avg_err = 0.0;
  3230. int first_err_n = -1;
  3231. int first_err_m = -1;
  3232. int first_err_b = -1;
  3233. for (size_t i = 0; i < m*n*batch; i++) {
  3234. double err = std::fabs(d[i] - d_chk[i]);
  3235. avg_err += err;
  3236. if (err > 0.05f && first_err_n == -1) {
  3237. first_err_b = i / (m * n);
  3238. first_err_n = (i % (m * n)) / m;
  3239. first_err_m = (i % (m * n)) % m;
  3240. }
  3241. }
  3242. avg_err /= m * n;
  3243. std::cerr << "TEST " << shname << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time / num_it << "ms avg_err=" << avg_err << std::endl;
  3244. if (avg_err > 0.1) {
  3245. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  3246. std::cerr << "Actual result: " << std::endl << std::endl;
  3247. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3248. std::cerr << std::endl;
  3249. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n + 15, first_err_b);
  3250. std::cerr << "Expected result: " << std::endl << std::endl;
  3251. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3252. if (split_k > 1) {
  3253. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  3254. ggml_vk_buffer_read(ctx, ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  3255. std::cerr << "d_buf0: " << std::endl << std::endl;
  3256. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3257. std::cerr << "d_buf1: " << std::endl << std::endl;
  3258. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3259. std::cerr << "d_buf2: " << std::endl << std::endl;
  3260. 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);
  3261. std::cerr << "d_buf3: " << std::endl << std::endl;
  3262. 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);
  3263. free(split_k_buf);
  3264. }
  3265. }
  3266. free(d_chk);
  3267. ggml_vk_queue_cleanup(ctx, ctx->device->transfer_queue);
  3268. ggml_vk_queue_cleanup(ctx, ctx->device->compute_queue);
  3269. ggml_vk_destroy_buffer(d_X);
  3270. ggml_vk_destroy_buffer(d_Y);
  3271. ggml_vk_destroy_buffer(d_D);
  3272. ggml_pipeline_cleanup(p);
  3273. ggml_pipeline_cleanup(ctx->device->pipeline_matmul_split_k_reduce);
  3274. free(x);
  3275. free(y);
  3276. free(d);
  3277. }
  3278. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  3279. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  3280. return;
  3281. }
  3282. i0 = std::max(i0, 5);
  3283. i1 = std::max(i1, 5);
  3284. i2 = std::max(i2, 0);
  3285. i3 = std::max(i3, 0);
  3286. fprintf(stderr, " ");
  3287. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  3288. fprintf(stderr, "%7d ", idx1);
  3289. }
  3290. fprintf(stderr, "\n");
  3291. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  3292. fprintf(stderr, "%7d: ", idx0);
  3293. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  3294. 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]) {
  3295. float val;
  3296. if (tensor->type == GGML_TYPE_F32) {
  3297. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  3298. } else if (tensor->type == GGML_TYPE_F16) {
  3299. 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]));
  3300. }
  3301. fprintf(stderr, "% 7.2f ", val);
  3302. } else {
  3303. fprintf(stderr, " ");
  3304. }
  3305. }
  3306. fprintf(stderr, "\n");
  3307. }
  3308. }
  3309. static void ggml_vk_test_h2d_nc(ggml_backend_vk_context * ctx, size_t ne0, size_t ne1, size_t ne2, size_t ne3) {
  3310. const size_t ne = ne0 * ne1 * ne2 * ne3;
  3311. ggml_init_params iparams = {
  3312. /*.mem_size =*/ 1024*1024*1024,
  3313. /*.mem_buffer =*/ NULL,
  3314. /*.no_alloc =*/ true,
  3315. };
  3316. ggml_context * ggml_ctx = ggml_init(iparams);
  3317. ggml_tensor * tensor = ggml_new_tensor_4d(ggml_ctx, GGML_TYPE_F32, ne0, ne2, ne1, ne3); // NOLINT
  3318. ggml_tensor * result_tensor = ggml_new_tensor_4d(ggml_ctx, GGML_TYPE_F32, ne0, ne1, ne2, ne3);
  3319. float * data = (float *) ggml_vk_host_malloc(ctx, ggml_nbytes(tensor));
  3320. tensor->data = data;
  3321. float * result_data = (float *) malloc(ggml_nbytes(tensor));
  3322. result_tensor->data = result_data;
  3323. // Permute
  3324. {
  3325. size_t tmp = tensor->nb[2];
  3326. tensor->nb[2] = tensor->nb[1];
  3327. tensor->nb[1] = tmp;
  3328. tensor->ne[2] = ne2;
  3329. tensor->ne[1] = ne1;
  3330. }
  3331. for (size_t i = 0; i < ne; i++) {
  3332. data[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  3333. }
  3334. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  3335. ggml_vk_ctx_begin(ctx, subctx);
  3336. vk_buffer buffer = ggml_vk_create_buffer_check(ctx, ggml_nbytes(tensor), vk::MemoryPropertyFlagBits::eDeviceLocal);
  3337. ggml_vk_h2d_tensor_2d(ctx, subctx, buffer, 0, tensor, 0, 0, ggml_nrows(tensor));
  3338. ggml_vk_ctx_end(subctx);
  3339. ggml_vk_submit(subctx, ctx->fence);
  3340. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_h2d_nc waitForFences");
  3341. ctx->device->device.resetFences({ ctx->fence });
  3342. ggml_vk_buffer_read(ctx, buffer, 0, result_data, ggml_nbytes(tensor));
  3343. double avg_err = 0.0;
  3344. int first_err_i0 = -1;
  3345. int first_err_i1 = -1;
  3346. int first_err_i2 = -1;
  3347. int first_err_i3 = -1;
  3348. for (size_t i3 = 0; i3 < ne3; i3++) {
  3349. for (size_t i2 = 0; i2 < ne2; i2++) {
  3350. for (size_t i1 = 0; i1 < ne1; i1++) {
  3351. for (size_t i0 = 0; i0 < ne0; i0++) {
  3352. float correct = *(float *) ((char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  3353. float result = *(float *) ((char *) result_data + i3*ne2*ne1*ne0*sizeof(float) + i2*ne1*ne0*sizeof(float) + i1*ne0*sizeof(float) + i0*sizeof(float));
  3354. double err = std::fabs(result - correct);
  3355. avg_err += err;
  3356. if (err > 0.05f && first_err_i0 == -1) {
  3357. first_err_i0 = i0;
  3358. first_err_i1 = i1;
  3359. first_err_i2 = i2;
  3360. first_err_i3 = i3;
  3361. }
  3362. }
  3363. }
  3364. }
  3365. }
  3366. avg_err /= ne;
  3367. std::cerr << "TEST nc copy ne0=" << ne0 << " ne1=" << ne1 << " ne2=" << ne2 << " ne3=" << ne3 << " avg_err=" << avg_err << std::endl;
  3368. if (avg_err > 0.1) {
  3369. std::cerr << "i0 = " << first_err_i0 << " i1 = " << first_err_i1 << " i2 = " << first_err_i2 << " i3 = " << first_err_i3 << std::endl;
  3370. std::cerr << "Actual result: " << std::endl << std::endl;
  3371. ggml_vk_print_tensor_area(result_tensor, first_err_i0, first_err_i1, first_err_i2, first_err_i3);
  3372. std::cerr << "Expected result: " << std::endl << std::endl;
  3373. ggml_vk_print_tensor_area(tensor, first_err_i0, first_err_i1, first_err_i2, first_err_i3);
  3374. }
  3375. ggml_free(ggml_ctx);
  3376. ggml_vk_destroy_buffer(buffer);
  3377. ggml_vk_host_free(ctx, data);
  3378. free(result_data);
  3379. }
  3380. static void ggml_vk_test_transfer(ggml_backend_vk_context * ctx, size_t ne, bool pinned) {
  3381. #ifdef GGML_VULKAN_DEBUG
  3382. std::cerr << "ggml_vk_test_transfer(" << ne << ")" << std::endl;
  3383. #endif
  3384. // Check transfers are correct
  3385. vk_buffer buffer = ggml_vk_create_buffer_check(ctx, sizeof(float) * ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3386. float * x;
  3387. float * y;
  3388. if (pinned) {
  3389. x = (float *) ggml_vk_host_malloc(ctx, sizeof(float) * ne);
  3390. y = (float *) ggml_vk_host_malloc(ctx, sizeof(float) * ne);
  3391. } else {
  3392. x = (float *) malloc(sizeof(float) * ne);
  3393. y = (float *) malloc(sizeof(float) * ne);
  3394. }
  3395. for (size_t i = 0; i < ne; i++) {
  3396. x[i] = rand() / (float)RAND_MAX;
  3397. }
  3398. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  3399. ggml_vk_ctx_begin(ctx, subctx);
  3400. auto begin = std::chrono::high_resolution_clock::now();
  3401. ggml_vk_buffer_write_async(ctx, subctx, buffer, 0, x, sizeof(float) * ne);
  3402. for (auto& cpy : subctx->in_memcpys) {
  3403. memcpy(cpy.dst, cpy.src, cpy.n);
  3404. }
  3405. subctx->in_memcpys.clear();
  3406. ggml_vk_ctx_end(subctx);
  3407. ggml_vk_submit(subctx, ctx->fence);
  3408. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_transfer waitForFences");
  3409. ctx->device->device.resetFences({ ctx->fence });
  3410. auto end = std::chrono::high_resolution_clock::now();
  3411. double ms_to_gpu = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3412. ggml_vk_ctx_begin(ctx, subctx);
  3413. begin = std::chrono::high_resolution_clock::now();
  3414. ggml_vk_buffer_read_async(ctx, subctx, buffer, 0, y, sizeof(float) * ne);
  3415. ggml_vk_ctx_end(subctx);
  3416. ggml_vk_submit(subctx, ctx->fence);
  3417. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_transfer waitForFences");
  3418. ctx->device->device.resetFences({ ctx->fence });
  3419. for (auto& cpy : subctx->out_memcpys) {
  3420. memcpy(cpy.dst, cpy.src, cpy.n);
  3421. }
  3422. subctx->out_memcpys.clear();
  3423. end = std::chrono::high_resolution_clock::now();
  3424. double ms_from_gpu = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3425. double avg_err = 0.0;
  3426. for (size_t i = 0; i < ne; i++) {
  3427. avg_err += std::fabs(x[i] - y[i]);
  3428. }
  3429. double kb = ne * sizeof(float) / 1024.0;
  3430. std::cerr << "TEST TRANSFER " << kb << " KB to_gpu " << ms_to_gpu << "ms (" << kb / ms_to_gpu * 1000.0 / 1024.0 << " MB/s) from_gpu " << ms_from_gpu << "ms (" << kb / ms_from_gpu * 1000.0 / 1024.0 << " MB/s) avg_err=" << avg_err / ne << std::endl;
  3431. ggml_vk_destroy_buffer(buffer);
  3432. if (pinned) {
  3433. ggml_vk_host_free(ctx, x);
  3434. ggml_vk_host_free(ctx, y);
  3435. } else {
  3436. free(x);
  3437. free(y);
  3438. }
  3439. }
  3440. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  3441. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  3442. }
  3443. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  3444. #ifdef GGML_VULKAN_DEBUG
  3445. std::cerr << "ggml_vk_test_dequant(" << ne << ")" << std::endl;
  3446. #endif
  3447. const size_t x_sz = sizeof(float) * ne;
  3448. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  3449. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  3450. float * x = (float *) malloc(x_sz);
  3451. void * qx = malloc(qx_sz);
  3452. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3453. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx, x_sz_f16, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3454. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  3455. for (size_t i = 0; i < ne; i++) {
  3456. x[i] = rand() / (float)RAND_MAX;
  3457. }
  3458. vk_pipeline p = ctx->device->pipeline_dequant[quant];
  3459. ggml_vk_quantize_data(x, qx, ne, quant);
  3460. ggml_pipeline_allocate_descriptor_sets(ctx, p, 1);
  3461. ggml_vk_buffer_write(ctx, qx_buf, 0, qx, qx_sz);
  3462. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  3463. ggml_vk_ctx_begin(ctx, subctx);
  3464. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  3465. ggml_vk_dispatch_pipeline(ctx, subctx, p, { { qx_buf, 0, qx_sz }, { x_buf, 0, x_sz_f16 } }, pc.size() * sizeof(int), pc.data(), { (uint32_t)ne, 1, 1});
  3466. ggml_vk_ctx_end(subctx);
  3467. auto begin = std::chrono::high_resolution_clock::now();
  3468. ggml_vk_submit(subctx, ctx->fence);
  3469. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  3470. ctx->device->device.resetFences({ ctx->fence });
  3471. auto end = std::chrono::high_resolution_clock::now();
  3472. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3473. ggml_vk_buffer_read(ctx, x_buf, 0, x_chk, x_sz_f16);
  3474. int first_err = -1;
  3475. double avg_err = 0.0;
  3476. for (size_t i = 0; i < ne; i++) {
  3477. double error = std::fabs(x[i] - ggml_fp16_to_fp32(x_chk[i]));
  3478. avg_err += error;
  3479. if (first_err < 0 && error > 0.05) {
  3480. first_err = i;
  3481. }
  3482. }
  3483. avg_err /= ne;
  3484. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  3485. if (avg_err > 0.1) {
  3486. std::cerr << "first_error = " << first_err << std::endl;
  3487. std::cerr << "Actual result: " << std::endl << std::endl;
  3488. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  3489. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  3490. }
  3491. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  3492. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  3493. std::cerr << x[i] << ", ";
  3494. }
  3495. std::cerr << std::endl;
  3496. }
  3497. ggml_vk_destroy_buffer(x_buf);
  3498. ggml_vk_destroy_buffer(qx_buf);
  3499. free(x);
  3500. free(qx);
  3501. free(x_chk);
  3502. }
  3503. 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) {
  3504. #ifdef GGML_VULKAN_DEBUG
  3505. std::cerr << "ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")" << std::endl;
  3506. #endif
  3507. const size_t x_ne = m * k * batch;
  3508. const size_t y_ne = k * n * batch;
  3509. const size_t d_ne = m * n * batch;
  3510. vk_pipeline p;
  3511. std::string shname;
  3512. if (shader_size == 0) {
  3513. p = ctx->device->pipeline_dequant_mul_mat_mat[quant]->a_s;
  3514. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  3515. } else if (shader_size == 1) {
  3516. p = ctx->device->pipeline_dequant_mul_mat_mat[quant]->a_m;
  3517. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  3518. } else if (shader_size == 2) {
  3519. p = ctx->device->pipeline_dequant_mul_mat_mat[quant]->a_l;
  3520. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  3521. } else {
  3522. GGML_ASSERT(0);
  3523. }
  3524. const size_t kpad = ggml_vk_align_size(k, p->align);
  3525. if (k != kpad) {
  3526. if (shader_size == 0) {
  3527. p = ctx->device->pipeline_dequant_mul_mat_mat[quant]->s;
  3528. shname = std::string(ggml_type_name(quant)) + "_S";
  3529. } else if (shader_size == 1) {
  3530. p = ctx->device->pipeline_dequant_mul_mat_mat[quant]->m;
  3531. shname = std::string(ggml_type_name(quant)) + "_M";
  3532. } else if (shader_size == 2) {
  3533. p = ctx->device->pipeline_dequant_mul_mat_mat[quant]->l;
  3534. shname = std::string(ggml_type_name(quant)) + "_L";
  3535. } else {
  3536. GGML_ASSERT(0);
  3537. }
  3538. }
  3539. const size_t x_sz = sizeof(float) * x_ne;
  3540. const size_t y_sz = sizeof(float) * y_ne;
  3541. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  3542. const size_t d_sz = sizeof(float) * d_ne;
  3543. float * x = (float *) malloc(x_sz);
  3544. float * y = (float *) malloc(y_sz);
  3545. void * qx = malloc(qx_sz);
  3546. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3547. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx, y_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3548. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx, d_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3549. float * d = (float *) malloc(d_sz);
  3550. float * d_chk = (float *) malloc(d_sz);
  3551. for (size_t i = 0; i < x_ne; i++) {
  3552. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  3553. }
  3554. ggml_vk_quantize_data(x, qx, x_ne, quant);
  3555. for (size_t i = 0; i < y_ne; i++) {
  3556. // y[i] = rand() / (float)RAND_MAX;
  3557. y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  3558. }
  3559. ggml_pipeline_allocate_descriptor_sets(ctx, p, num_it);
  3560. if (split_k > 1) {
  3561. ggml_pipeline_allocate_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  3562. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  3563. // Resize buffer
  3564. if (ctx->prealloc_split_k != nullptr) {
  3565. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  3566. }
  3567. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  3568. }
  3569. }
  3570. ggml_vk_buffer_write(ctx, qx_buf, 0, qx, qx_sz);
  3571. ggml_vk_buffer_write(ctx, y_buf, 0, y, y_sz);
  3572. vk_context * subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  3573. for (size_t i = 0; i < num_it; i++) {
  3574. ggml_vk_ctx_begin(ctx, subctx);
  3575. ggml_vk_matmul(ctx, subctx, p, ggml_vk_subbuffer(qx_buf), ggml_vk_subbuffer(y_buf), ggml_vk_subbuffer(d_buf), ggml_vk_subbuffer(ctx->prealloc_split_k), m, n, k, k, k, m, split_k, batch, batch, batch, 1, 1, k*m, k*n, m*n);
  3576. ggml_vk_ctx_end(subctx);
  3577. }
  3578. auto begin = std::chrono::high_resolution_clock::now();
  3579. ggml_vk_submit(subctx, ctx->fence);
  3580. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  3581. ctx->device->device.resetFences({ ctx->fence });
  3582. auto end = std::chrono::high_resolution_clock::now();
  3583. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  3584. ggml_vk_buffer_read(ctx, d_buf, 0, d, d_sz);
  3585. ggml_init_params iparams = {
  3586. /*.mem_size =*/ 1024*1024*1024,
  3587. /*.mem_buffer =*/ NULL,
  3588. /*.no_alloc =*/ true,
  3589. };
  3590. ggml_context * ggml_ctx = ggml_init(iparams);
  3591. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  3592. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  3593. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  3594. src0_ggml->data = qx;
  3595. src1_ggml->data = y;
  3596. tensor_ggml->data = d_chk;
  3597. ctx->disable = true;
  3598. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  3599. ggml_build_forward_expand(cgraph, tensor_ggml);
  3600. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  3601. ctx->disable = false;
  3602. ggml_free(ggml_ctx);
  3603. double avg_err = 0.0;
  3604. int first_err_n = -1;
  3605. int first_err_m = -1;
  3606. int first_err_b = -1;
  3607. for (size_t i = 0; i < m*n*batch; i++) {
  3608. double err = std::fabs(d[i] - d_chk[i]);
  3609. avg_err += err;
  3610. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  3611. first_err_b = i / (m * n);
  3612. first_err_n = (i % (m * n)) / m;
  3613. first_err_m = (i % (m * n)) % m;
  3614. }
  3615. }
  3616. avg_err /= m * n;
  3617. std::cerr << "TEST MMQ " << shname << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time_ms / num_it << "ms avg_err=" << avg_err << std::endl;
  3618. if (avg_err > 0.1 || std::isnan(avg_err)) {
  3619. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  3620. std::cerr << "Actual result: " << std::endl << std::endl;
  3621. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3622. std::cerr << std::endl;
  3623. std::cerr << "Expected result: " << std::endl << std::endl;
  3624. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3625. if (split_k > 1) {
  3626. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  3627. ggml_vk_buffer_read(ctx, ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  3628. std::cerr << "d_buf0: " << std::endl << std::endl;
  3629. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3630. std::cerr << "d_buf1: " << std::endl << std::endl;
  3631. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  3632. std::cerr << "d_buf2: " << std::endl << std::endl;
  3633. 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);
  3634. std::cerr << "d_buf3: " << std::endl << std::endl;
  3635. 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);
  3636. free(split_k_buf);
  3637. }
  3638. }
  3639. ggml_vk_destroy_buffer(qx_buf);
  3640. ggml_vk_destroy_buffer(y_buf);
  3641. ggml_vk_destroy_buffer(d_buf);
  3642. free(x);
  3643. free(qx);
  3644. free(y);
  3645. free(d);
  3646. free(d_chk);
  3647. }
  3648. #endif
  3649. static ggml_tensor_extra_gpu * ggml_vk_tensor_create_extra(ggml_tensor * tensor) {
  3650. #ifdef GGML_VULKAN_DEBUG
  3651. std::cerr << "ggml_vk_create_extra(" << tensor << " (" << tensor->name << ", " << ggml_op_name(tensor->op) << "))" << std::endl;
  3652. #endif
  3653. ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu;
  3654. extra->reset();
  3655. tensor->extra = extra;
  3656. return extra;
  3657. }
  3658. static bool ggml_vk_cpu_assist_op(const ggml_tensor * node) {
  3659. return node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID;
  3660. }
  3661. static void ggml_vk_preallocate_buffers_graph(ggml_backend_vk_context * ctx, ggml_tensor * node){
  3662. #ifdef GGML_VULKAN_DEBUG
  3663. std::cerr << "ggml_vk_preallocate_buffers_graph(" << node << ")" << std::endl;
  3664. #endif
  3665. const bool any_on_device = node->backend == GGML_BACKEND_TYPE_GPU
  3666. || (node->src[0] != nullptr && (node->src[0]->backend == GGML_BACKEND_TYPE_GPU || node->src[0]->backend == GGML_BACKEND_TYPE_GPU_SPLIT))
  3667. || (node->src[1] != nullptr && (node->src[1]->backend == GGML_BACKEND_TYPE_GPU));
  3668. if (ctx->disable || (!any_on_device && !ggml_vk_cpu_assist_op(node))) {
  3669. return;
  3670. }
  3671. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) node->extra;
  3672. if (extra == nullptr) {
  3673. // Workaround for CPU backend BLAS matmul calls
  3674. extra = ggml_vk_tensor_create_extra(node);
  3675. }
  3676. ggml_tensor * src0 = node->src[0];
  3677. ggml_tensor * src1 = node->src[1];
  3678. const bool use_src0 = src0 != nullptr;
  3679. const int64_t ne00 = use_src0 ? src0->ne[0] : 0;
  3680. const int64_t ne01 = use_src0 ? src0->ne[1] : 0;
  3681. const int64_t ne02 = use_src0 ? src0->ne[2] : 0;
  3682. const int64_t ne03 = use_src0 ? src0->ne[3] : 0;
  3683. const bool use_src1 = src1 != nullptr && node->op != GGML_OP_CPY && node->op != GGML_OP_CONT && node->op != GGML_OP_DUP;
  3684. const int64_t ne10 = use_src1 ? src1->ne[0] : 0;
  3685. const int64_t ne11 = use_src1 ? src1->ne[1] : 0;
  3686. const int64_t ne12 = use_src1 ? src1->ne[2] : 0;
  3687. const int64_t ne13 = use_src1 ? src1->ne[3] : 0;
  3688. const int64_t ne20 = node->ne[0];
  3689. const int64_t ne21 = node->ne[1];
  3690. const int64_t ne22 = node->ne[2];
  3691. const int64_t ne23 = node->ne[3];
  3692. const bool f16_f32_kernel = use_src1 && src1->type == GGML_TYPE_F32;
  3693. int split_k;
  3694. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  3695. split_k = ggml_vk_guess_split_k(ne01, ne11, ne10);
  3696. } else {
  3697. split_k = 1;
  3698. }
  3699. const uint32_t x_ne = ne00 * ne01;
  3700. const uint32_t y_ne = ne10 * ne11;
  3701. const uint32_t d_ne = ne20 * ne21;
  3702. const uint64_t qx_sz = use_src0 ? ggml_vk_align_size(ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ne02 * ne03 : 0;
  3703. const uint64_t qy_sz = use_src1 ? ggml_vk_align_size(ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type), ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ne12 * ne13 : 0;
  3704. const uint64_t x_sz = use_src0 ? ggml_vk_align_size(sizeof(ggml_fp16_t) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ne02 * ne03 : 0;
  3705. const uint64_t y_sz = use_src1 ? ggml_vk_align_size(f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ne12 * ne13 : 0;
  3706. uint64_t d_sz = ggml_vk_align_size(ggml_type_size(node->type) * d_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ne22 * ne23;
  3707. const uint64_t split_k_size = split_k > 1 ? d_sz * 4 : 0;
  3708. if (extra->buffer_gpu.expired()) {
  3709. // Workaround for CPU backend BLAS matmul calls
  3710. extra->buffer_gpu = ggml_vk_create_buffer_temp(ctx, d_sz);
  3711. }
  3712. switch (node->op) {
  3713. case GGML_OP_REPEAT:
  3714. case GGML_OP_GET_ROWS:
  3715. case GGML_OP_RESHAPE:
  3716. case GGML_OP_VIEW:
  3717. case GGML_OP_PERMUTE:
  3718. case GGML_OP_TRANSPOSE:
  3719. case GGML_OP_ADD:
  3720. case GGML_OP_SCALE:
  3721. case GGML_OP_SQR:
  3722. case GGML_OP_CLAMP:
  3723. case GGML_OP_CPY:
  3724. case GGML_OP_CONT:
  3725. case GGML_OP_DUP:
  3726. case GGML_OP_MUL:
  3727. case GGML_OP_NORM:
  3728. case GGML_OP_RMS_NORM:
  3729. case GGML_OP_DIAG_MASK_INF:
  3730. case GGML_OP_SOFT_MAX:
  3731. case GGML_OP_ROPE:
  3732. case GGML_OP_ARGSORT:
  3733. break;
  3734. case GGML_OP_UNARY:
  3735. switch (ggml_get_unary_op(node)) {
  3736. case GGML_UNARY_OP_SILU:
  3737. case GGML_UNARY_OP_GELU:
  3738. case GGML_UNARY_OP_RELU:
  3739. break;
  3740. default:
  3741. return;
  3742. }
  3743. break;
  3744. case GGML_OP_MUL_MAT:
  3745. case GGML_OP_MUL_MAT_ID:
  3746. if (ctx->prealloc_size_qx < qx_sz) {
  3747. ctx->prealloc_size_qx = qx_sz;
  3748. }
  3749. if (ctx->prealloc_size_qy < qy_sz) {
  3750. ctx->prealloc_size_qy = qy_sz;
  3751. }
  3752. if (ctx->prealloc_size_x < x_sz) {
  3753. ctx->prealloc_size_x = x_sz;
  3754. }
  3755. if (ctx->prealloc_size_y < y_sz) {
  3756. ctx->prealloc_size_y = y_sz;
  3757. }
  3758. if (ctx->prealloc_size_split_k < split_k_size) {
  3759. ctx->prealloc_size_split_k = split_k_size;
  3760. }
  3761. if (ctx->staging_size < x_sz + y_sz) {
  3762. ctx->staging_size = x_sz + y_sz;
  3763. }
  3764. break;
  3765. default:
  3766. return;
  3767. }
  3768. }
  3769. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  3770. if (ctx->disable) {
  3771. return;
  3772. }
  3773. #ifdef GGML_VULKAN_DEBUG
  3774. std::cerr << "ggml_vk_preallocate_buffers(qx_size: " << ctx->prealloc_size_qx << " qy_size: " << ctx->prealloc_size_qy << " x_size: " << ctx->prealloc_size_x << " y_size: " << ctx->prealloc_size_y << " split_k_size: " << ctx->prealloc_size_split_k << ")" << std::endl;
  3775. #endif
  3776. #if defined(GGML_VULKAN_RUN_TESTS)
  3777. ctx->staging = ggml_vk_create_buffer_check(ctx, 100ul * 1024ul * 1024ul,
  3778. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  3779. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  3780. ggml_vk_test_transfer(ctx, 8192 * 1000, false);
  3781. ggml_vk_test_transfer(ctx, 8192 * 1000, true);
  3782. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_F32);
  3783. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q4_0);
  3784. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q4_1);
  3785. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q5_0);
  3786. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q5_1);
  3787. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q8_0);
  3788. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q2_K);
  3789. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q3_K);
  3790. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q4_K);
  3791. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q5_K);
  3792. ggml_vk_test_dequant(ctx, 7680, GGML_TYPE_Q6_K);
  3793. ggml_vk_test_matmul<float, float>(ctx, 128, 512, 512, 2, 100, 1, 0);
  3794. ggml_vk_test_matmul<float, float>(ctx, 128, 512, 512, 2, 100, 1, 1);
  3795. ggml_vk_test_matmul<float, float>(ctx, 128, 512, 512, 2, 100, 1, 2);
  3796. ggml_vk_test_matmul<float, float>(ctx, 128, 512, 512, 2, 100, 4, 0);
  3797. ggml_vk_test_matmul<float, float>(ctx, 128, 512, 512, 2, 100, 4, 1);
  3798. ggml_vk_test_matmul<float, float>(ctx, 128, 512, 512, 2, 100, 4, 2);
  3799. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 0, GGML_TYPE_Q4_0);
  3800. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 1, GGML_TYPE_Q4_0);
  3801. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 2, GGML_TYPE_Q4_0);
  3802. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 0, GGML_TYPE_Q4_0);
  3803. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 1, GGML_TYPE_Q4_0);
  3804. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 2, GGML_TYPE_Q4_0);
  3805. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 0, GGML_TYPE_Q4_1);
  3806. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 1, GGML_TYPE_Q4_1);
  3807. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 2, GGML_TYPE_Q4_1);
  3808. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 0, GGML_TYPE_Q4_1);
  3809. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 1, GGML_TYPE_Q4_1);
  3810. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 2, GGML_TYPE_Q4_1);
  3811. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 0, GGML_TYPE_Q5_0);
  3812. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 1, GGML_TYPE_Q5_0);
  3813. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 2, GGML_TYPE_Q5_0);
  3814. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 0, GGML_TYPE_Q5_0);
  3815. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 1, GGML_TYPE_Q5_0);
  3816. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 2, GGML_TYPE_Q5_0);
  3817. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 0, GGML_TYPE_Q5_1);
  3818. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 1, GGML_TYPE_Q5_1);
  3819. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 2, GGML_TYPE_Q5_1);
  3820. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 0, GGML_TYPE_Q5_1);
  3821. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 1, GGML_TYPE_Q5_1);
  3822. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 2, GGML_TYPE_Q5_1);
  3823. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 0, GGML_TYPE_Q8_0);
  3824. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 1, GGML_TYPE_Q8_0);
  3825. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 1, 2, GGML_TYPE_Q8_0);
  3826. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 0, GGML_TYPE_Q8_0);
  3827. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 1, GGML_TYPE_Q8_0);
  3828. ggml_vk_test_dequant_matmul(ctx, 128, 512, 512, 2, 100, 4, 2, GGML_TYPE_Q8_0);
  3829. std::cerr << std::endl;
  3830. const std::vector<size_t> vals {
  3831. 8, 8, 8,
  3832. 100, 46, 576,
  3833. 623, 111, 128,
  3834. 100, 46, 558,
  3835. 512, 1, 256,
  3836. 128, 110, 622,
  3837. 511, 511, 127,
  3838. 511, 511, 7,
  3839. 511, 511, 17,
  3840. 49, 49, 128,
  3841. 128, 49, 49,
  3842. 4096, 49, 4096,
  3843. 11008, 49, 4096,
  3844. 4096, 49, 11008,
  3845. 32000, 49, 4096,
  3846. 512, 512, 128,
  3847. 128, 512, 512,
  3848. 4096, 512, 4096,
  3849. 11008, 512, 4096,
  3850. 4096, 512, 11008,
  3851. 32000, 512, 4096,
  3852. };
  3853. const size_t num_it = 1;
  3854. for (size_t i = 0; i < vals.size(); i += 3) {
  3855. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  3856. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  3857. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  3858. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  3859. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  3860. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  3861. std::cerr << std::endl;
  3862. }
  3863. GGML_ASSERT(false);
  3864. #endif
  3865. if (ctx->prealloc_qx == nullptr || (ctx->prealloc_size_qx > 0 && ctx->prealloc_qx->size < ctx->prealloc_size_qx)) {
  3866. // Resize buffer
  3867. if (ctx->prealloc_qx != nullptr) {
  3868. ggml_vk_destroy_buffer(ctx->prealloc_qx);
  3869. }
  3870. ctx->prealloc_qx = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_qx);
  3871. }
  3872. if (ctx->prealloc_qy == nullptr || (ctx->prealloc_size_qy > 0 && ctx->prealloc_qy->size < ctx->prealloc_size_qy)) {
  3873. // Resize buffer
  3874. if (ctx->prealloc_qy != nullptr) {
  3875. ggml_vk_destroy_buffer(ctx->prealloc_qy);
  3876. }
  3877. ctx->prealloc_qy = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_qy);
  3878. }
  3879. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  3880. // Resize buffer
  3881. if (ctx->prealloc_x != nullptr) {
  3882. ggml_vk_destroy_buffer(ctx->prealloc_x);
  3883. }
  3884. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_x);
  3885. }
  3886. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  3887. // Resize buffer
  3888. if (ctx->prealloc_y != nullptr) {
  3889. ggml_vk_destroy_buffer(ctx->prealloc_y);
  3890. }
  3891. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_y);
  3892. }
  3893. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  3894. // Resize buffer
  3895. if (ctx->prealloc_split_k != nullptr) {
  3896. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  3897. }
  3898. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx, ctx->prealloc_size_split_k);
  3899. }
  3900. if (ctx->staging == nullptr || (ctx->staging_size > 0 && ctx->staging->size < ctx->staging_size)) {
  3901. // Resize buffer
  3902. if (ctx->staging != nullptr) {
  3903. ggml_vk_destroy_buffer(ctx->staging);
  3904. }
  3905. ctx->staging = ggml_vk_create_buffer_check(ctx, ctx->staging_size,
  3906. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  3907. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  3908. }
  3909. }
  3910. static void ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_tensor * node, bool last_node){
  3911. const bool any_on_device = node->backend == GGML_BACKEND_TYPE_GPU
  3912. || (node->src[0] != nullptr && (node->src[0]->backend == GGML_BACKEND_TYPE_GPU || node->src[0]->backend == GGML_BACKEND_TYPE_GPU_SPLIT))
  3913. || (node->src[1] != nullptr && node->src[1]->backend == GGML_BACKEND_TYPE_GPU);
  3914. if (ctx->disable || (!any_on_device && !ggml_vk_cpu_assist_op(node)) || (ggml_vk_cpu_assist_op(node) && !any_on_device && !ggml_vk_can_mul_mat(node->src[0], node->src[1], node))) {
  3915. return;
  3916. }
  3917. #ifdef GGML_VULKAN_DEBUG
  3918. std::cerr << "ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")" << std::endl;
  3919. #endif
  3920. ctx->semaphore_idx = 0;
  3921. ctx->staging_offset = 0;
  3922. const ggml_tensor * src0 = node->src[0];
  3923. const ggml_tensor * src1 = node->src[1];
  3924. const ggml_tensor * src2 = node->src[2];
  3925. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) node->extra;
  3926. switch (node->op) {
  3927. case GGML_OP_UNARY:
  3928. switch (ggml_get_unary_op(node)) {
  3929. case GGML_UNARY_OP_SILU:
  3930. case GGML_UNARY_OP_GELU:
  3931. case GGML_UNARY_OP_RELU:
  3932. break;
  3933. default:
  3934. return;
  3935. }
  3936. break;
  3937. case GGML_OP_REPEAT:
  3938. // case GGML_OP_GET_ROWS:
  3939. case GGML_OP_ADD:
  3940. case GGML_OP_MUL:
  3941. case GGML_OP_SCALE:
  3942. case GGML_OP_SQR:
  3943. case GGML_OP_CLAMP:
  3944. case GGML_OP_CPY:
  3945. case GGML_OP_CONT:
  3946. case GGML_OP_DUP:
  3947. case GGML_OP_RESHAPE:
  3948. case GGML_OP_VIEW:
  3949. case GGML_OP_PERMUTE:
  3950. case GGML_OP_TRANSPOSE:
  3951. case GGML_OP_NORM:
  3952. case GGML_OP_RMS_NORM:
  3953. case GGML_OP_DIAG_MASK_INF:
  3954. case GGML_OP_SOFT_MAX:
  3955. case GGML_OP_ROPE:
  3956. case GGML_OP_MUL_MAT:
  3957. case GGML_OP_MUL_MAT_ID:
  3958. case GGML_OP_NONE:
  3959. case GGML_OP_ARGSORT:
  3960. break;
  3961. default:
  3962. if (any_on_device) {
  3963. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  3964. GGML_ASSERT(false);
  3965. }
  3966. return;
  3967. }
  3968. if (ctx->compute_ctx == nullptr) {
  3969. ctx->compute_ctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  3970. ggml_vk_ctx_begin(ctx, ctx->compute_ctx);
  3971. }
  3972. switch (node->op) {
  3973. case GGML_OP_REPEAT:
  3974. ggml_vk_repeat(ctx, ctx->compute_ctx, src0, src1, node);
  3975. break;
  3976. case GGML_OP_GET_ROWS:
  3977. ggml_vk_get_rows(ctx, ctx->compute_ctx, src0, src1, node);
  3978. break;
  3979. case GGML_OP_ADD:
  3980. ggml_vk_add(ctx, ctx->compute_ctx, src0, src1, node);
  3981. break;
  3982. case GGML_OP_MUL:
  3983. ggml_vk_mul(ctx, ctx->compute_ctx, src0, src1, node);
  3984. break;
  3985. case GGML_OP_SCALE:
  3986. ggml_vk_scale(ctx, ctx->compute_ctx, src0, node);
  3987. break;
  3988. case GGML_OP_SQR:
  3989. ggml_vk_sqr(ctx, ctx->compute_ctx, src0, node);
  3990. break;
  3991. case GGML_OP_CLAMP:
  3992. ggml_vk_clamp(ctx, ctx->compute_ctx, src0, node);
  3993. break;
  3994. case GGML_OP_CPY:
  3995. case GGML_OP_CONT:
  3996. case GGML_OP_DUP:
  3997. ggml_vk_cpy(ctx, ctx->compute_ctx, src0, node);
  3998. break;
  3999. case GGML_OP_RESHAPE:
  4000. case GGML_OP_VIEW:
  4001. case GGML_OP_PERMUTE:
  4002. case GGML_OP_TRANSPOSE:
  4003. case GGML_OP_NONE:
  4004. ggml_vk_nop(ctx, ctx->compute_ctx, src0, node);
  4005. break;
  4006. case GGML_OP_NORM:
  4007. ggml_vk_norm(ctx, ctx->compute_ctx, src0, node);
  4008. break;
  4009. case GGML_OP_RMS_NORM:
  4010. ggml_vk_rms_norm(ctx, ctx->compute_ctx, src0, node);
  4011. break;
  4012. case GGML_OP_UNARY:
  4013. switch (ggml_get_unary_op(node)) {
  4014. case GGML_UNARY_OP_SILU:
  4015. case GGML_UNARY_OP_GELU:
  4016. case GGML_UNARY_OP_RELU:
  4017. ggml_vk_unary(ctx, ctx->compute_ctx, src0, node);
  4018. break;
  4019. default:
  4020. return;
  4021. }
  4022. break;
  4023. case GGML_OP_DIAG_MASK_INF:
  4024. ggml_vk_diag_mask_inf(ctx, ctx->compute_ctx, src0, node);
  4025. break;
  4026. case GGML_OP_SOFT_MAX:
  4027. ggml_vk_soft_max(ctx, ctx->compute_ctx, src0, src1, src2, node);
  4028. break;
  4029. case GGML_OP_ROPE:
  4030. ggml_vk_rope(ctx, ctx->compute_ctx, src0, src1, node);
  4031. break;
  4032. case GGML_OP_ARGSORT:
  4033. ggml_vk_argsort(ctx, ctx->compute_ctx, src0, node);
  4034. break;
  4035. case GGML_OP_MUL_MAT:
  4036. ggml_vk_mul_mat(ctx, ctx->compute_ctx, src0, src1, node);
  4037. break;
  4038. case GGML_OP_MUL_MAT_ID:
  4039. //ggml_vk_mul_mat_id(ctx, ctx->compute_ctx, src0, src1, node);
  4040. std::cerr << "ggml_vulkan: GGML_OP_MUL_MAT_ID not implemented yet." << std::endl;
  4041. GGML_ASSERT(false);
  4042. break;
  4043. default:
  4044. return;
  4045. }
  4046. extra->ready = true;
  4047. extra->ctx_idx = ctx->compute_ctx->idx;
  4048. #ifdef GGML_VULKAN_CHECK_RESULTS
  4049. // Force context reset on each node so that each tensor ends up in its own context
  4050. // and can be run and compared to its CPU equivalent separately
  4051. last_node = true;
  4052. #endif
  4053. if (node->backend == GGML_BACKEND_TYPE_CPU || last_node) {
  4054. ggml_vk_ctx_end(ctx->compute_ctx);
  4055. ctx->compute_ctx->exit_tensor = node;
  4056. ctx->compute_ctx = nullptr;
  4057. }
  4058. }
  4059. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor){
  4060. const bool any_on_device = tensor->backend == GGML_BACKEND_TYPE_GPU
  4061. || (tensor->src[0] != nullptr && (tensor->src[0]->backend == GGML_BACKEND_TYPE_GPU || tensor->src[0]->backend == GGML_BACKEND_TYPE_GPU_SPLIT))
  4062. || (tensor->src[1] != nullptr && tensor->src[1]->backend == GGML_BACKEND_TYPE_GPU);
  4063. if (ctx->disable || (!any_on_device && !ggml_vk_cpu_assist_op(tensor))) {
  4064. return false;
  4065. }
  4066. ggml_tensor_extra_gpu * extra = nullptr;
  4067. switch (tensor->op) {
  4068. case GGML_OP_ADD:
  4069. case GGML_OP_GET_ROWS:
  4070. case GGML_OP_MUL:
  4071. case GGML_OP_SCALE:
  4072. case GGML_OP_SQR:
  4073. case GGML_OP_CLAMP:
  4074. case GGML_OP_CPY:
  4075. case GGML_OP_CONT:
  4076. case GGML_OP_DUP:
  4077. case GGML_OP_NORM:
  4078. case GGML_OP_RMS_NORM:
  4079. case GGML_OP_DIAG_MASK_INF:
  4080. case GGML_OP_SOFT_MAX:
  4081. case GGML_OP_ROPE:
  4082. case GGML_OP_RESHAPE:
  4083. case GGML_OP_VIEW:
  4084. case GGML_OP_PERMUTE:
  4085. case GGML_OP_TRANSPOSE:
  4086. case GGML_OP_NONE:
  4087. case GGML_OP_ARGSORT:
  4088. extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4089. break;
  4090. case GGML_OP_UNARY:
  4091. switch (ggml_get_unary_op(tensor)) {
  4092. case GGML_UNARY_OP_SILU:
  4093. case GGML_UNARY_OP_GELU:
  4094. case GGML_UNARY_OP_RELU:
  4095. extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4096. break;
  4097. default:
  4098. return false;
  4099. }
  4100. break;
  4101. case GGML_OP_MUL_MAT:
  4102. case GGML_OP_MUL_MAT_ID:
  4103. if (!any_on_device && !ggml_vk_can_mul_mat(tensor->src[0], tensor->src[1], tensor)) {
  4104. return false;
  4105. }
  4106. extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4107. break;
  4108. default:
  4109. return false;
  4110. }
  4111. if (extra == nullptr) {
  4112. return false;
  4113. }
  4114. if (params->ith != 0) {
  4115. return true;
  4116. }
  4117. if (params->type == GGML_TASK_TYPE_INIT || params->type == GGML_TASK_TYPE_FINALIZE) {
  4118. return true;
  4119. }
  4120. #ifdef GGML_VULKAN_DEBUG
  4121. std::cerr << "ggml_vk_compute_forward(" << tensor << ", name=" << tensor->name << ", op=" << ggml_op_name(tensor->op) << ", type=" << tensor->type << ", backend=" << tensor->backend << ", 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 << ")" << std::endl;
  4122. #endif
  4123. #ifdef GGML_VULKAN_CHECK_RESULTS
  4124. ggml_vk_check_results_0(ctx, params, tensor);
  4125. #endif
  4126. GGML_ASSERT(extra->ready);
  4127. vk_context& subctx = ctx->gc.contexts[extra->ctx_idx];
  4128. // Only run if ctx hasn't been submitted yet
  4129. if (!subctx.seqs.empty()) {
  4130. // Do staging buffer copies
  4131. for (auto& cpy : subctx.in_memcpys) {
  4132. memcpy(cpy.dst, cpy.src, cpy.n);
  4133. }
  4134. ggml_vk_submit(&subctx, ctx->fence);
  4135. }
  4136. if (tensor == subctx.exit_tensor) {
  4137. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_compute_forward waitForFences");
  4138. ctx->device->device.resetFences({ ctx->fence });
  4139. // Do staging buffer copies
  4140. for (auto& cpy : subctx.out_memcpys) {
  4141. memcpy(cpy.dst, cpy.src, cpy.n);
  4142. }
  4143. subctx.in_memcpys.clear();
  4144. subctx.out_memcpys.clear();
  4145. }
  4146. extra->ready = false;
  4147. return true;
  4148. }
  4149. // Clean up after graph processing is done
  4150. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  4151. if (ctx->disable) {
  4152. return;
  4153. }
  4154. #ifdef GGML_VULKAN_DEBUG
  4155. std::cerr << "ggml_vk_graph_cleanup()" << std::endl;
  4156. #endif
  4157. for (auto& buffer : ctx->gc.temp_buffers) {
  4158. ggml_vk_pool_free(ctx, buffer);
  4159. }
  4160. ctx->gc.temp_buffers.clear();
  4161. for (auto& pipeline : ctx->device->pipelines) {
  4162. if (pipeline.expired()) {
  4163. continue;
  4164. }
  4165. vk_pipeline pl = pipeline.lock();
  4166. ggml_pipeline_cleanup(pl);
  4167. }
  4168. ggml_vk_queue_cleanup(ctx, ctx->device->compute_queue);
  4169. ggml_vk_queue_cleanup(ctx, ctx->device->transfer_queue);
  4170. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  4171. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  4172. }
  4173. ctx->gc.semaphores.clear();
  4174. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  4175. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  4176. }
  4177. ctx->gc.tl_semaphores.clear();
  4178. ctx->semaphore_idx = 0;
  4179. ctx->event_idx = 0;
  4180. for (auto& event : ctx->gc.events) {
  4181. ctx->device->device.resetEvent(event);
  4182. }
  4183. ctx->staging_offset = 0;
  4184. ctx->compute_ctx = nullptr;
  4185. ctx->transfer_ctx = nullptr;
  4186. ctx->gc.contexts.clear();
  4187. }
  4188. // Clean up on backend free
  4189. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  4190. #ifdef GGML_VULKAN_DEBUG
  4191. std::cerr << "ggml_vk_cleanup(" << ctx->idx << ")" << std::endl;
  4192. #endif
  4193. ggml_vk_graph_cleanup(ctx);
  4194. ggml_vk_destroy_buffer(ctx->prealloc_qx);
  4195. ggml_vk_destroy_buffer(ctx->prealloc_qy);
  4196. ggml_vk_destroy_buffer(ctx->prealloc_x);
  4197. ggml_vk_destroy_buffer(ctx->prealloc_y);
  4198. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  4199. ggml_vk_destroy_buffer(ctx->staging);
  4200. ggml_vk_destroy_buffer(ctx->sync_staging);
  4201. for (auto& buffer : ctx->buffer_pool) {
  4202. ggml_vk_destroy_buffer(buffer);
  4203. }
  4204. ctx->prealloc_size_qx = 0;
  4205. ctx->prealloc_size_qy = 0;
  4206. ctx->prealloc_size_x = 0;
  4207. ctx->prealloc_size_y = 0;
  4208. ctx->prealloc_size_split_k = 0;
  4209. ctx->staging_size = 0;
  4210. for (auto& event : ctx->gc.events) {
  4211. ctx->device->device.destroyEvent(event);
  4212. }
  4213. ctx->gc.events.clear();
  4214. ctx->device->device.destroyFence(ctx->fence);
  4215. }
  4216. GGML_CALL static int ggml_vk_get_device_count() {
  4217. ggml_vk_instance_init();
  4218. return vk_instance.device_indices.size();
  4219. }
  4220. GGML_CALL static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  4221. ggml_vk_instance_init();
  4222. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4223. vk::PhysicalDeviceProperties props;
  4224. devices[device].getProperties(&props);
  4225. snprintf(description, description_size, "%s", props.deviceName.data());
  4226. }
  4227. // CPU assist interface
  4228. void ggml_vk_init_cpu_assist() {
  4229. ggml_vk_instance_init();
  4230. std::cerr << "ggml_vulkan: Found " << ggml_vk_get_device_count() << " Vulkan devices:" << std::endl;
  4231. for (int i = 0; i < ggml_vk_get_device_count(); i++) {
  4232. ggml_vk_print_gpu_info(i);
  4233. }
  4234. // Initialize the first backend to make sure CPU matrix multiplications can be offloaded.
  4235. ggml_backend_vk_init(0);
  4236. }
  4237. void ggml_vk_preallocate_buffers_graph_cpu_assist(ggml_tensor * node) {
  4238. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  4239. if (!ctx->initialized) {
  4240. return;
  4241. }
  4242. ggml_vk_preallocate_buffers_graph(ctx, node);
  4243. }
  4244. void ggml_vk_preallocate_buffers_cpu_assist() {
  4245. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  4246. if (!ctx->initialized) {
  4247. return;
  4248. }
  4249. ggml_vk_preallocate_buffers(ctx);
  4250. }
  4251. void ggml_vk_build_graph_cpu_assist(ggml_tensor * node, bool last_node) {
  4252. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  4253. if (!ctx->initialized) {
  4254. return;
  4255. }
  4256. ggml_vk_build_graph(ctx, node, last_node);
  4257. }
  4258. bool ggml_vk_compute_forward_cpu_assist(ggml_compute_params * params, ggml_tensor * tensor){
  4259. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  4260. if (!ctx->initialized) {
  4261. return false;
  4262. }
  4263. return ggml_vk_compute_forward(ctx, params, tensor);
  4264. }
  4265. void ggml_vk_graph_cleanup_cpu_assist() {
  4266. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  4267. if (!ctx->initialized) {
  4268. return;
  4269. }
  4270. ggml_vk_graph_cleanup(ctx);
  4271. }
  4272. void ggml_vk_free_cpu_assist() {
  4273. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  4274. if (!ctx->initialized || vk_instance.backends[0] == nullptr) {
  4275. return;
  4276. }
  4277. ggml_backend_vk_free(vk_instance.backends[0]);
  4278. }
  4279. // backend interface
  4280. #define UNUSED GGML_UNUSED
  4281. // device backend
  4282. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  4283. struct ggml_backend_vk_buffer_context {
  4284. ggml_backend_vk_context * ctx;
  4285. vk_buffer dev_buffer;
  4286. ggml_tensor_extra_gpu * temp_tensor_extras = nullptr;
  4287. size_t temp_tensor_extra_index = 0;
  4288. std::string name;
  4289. ggml_backend_vk_buffer_context(ggml_backend_vk_context * ctx, vk_buffer&& dev_buffer, std::string& name) :
  4290. ctx(ctx),
  4291. dev_buffer(dev_buffer),
  4292. name(name) {
  4293. }
  4294. ~ggml_backend_vk_buffer_context() {
  4295. ggml_vk_destroy_buffer(dev_buffer);
  4296. delete[] temp_tensor_extras;
  4297. }
  4298. ggml_tensor_extra_gpu * ggml_vk_alloc_temp_tensor_extra() {
  4299. if (temp_tensor_extras == nullptr) {
  4300. temp_tensor_extras = new ggml_tensor_extra_gpu[GGML_VK_MAX_NODES];
  4301. }
  4302. size_t alloc_index = temp_tensor_extra_index;
  4303. temp_tensor_extra_index = (temp_tensor_extra_index + 1) % GGML_VK_MAX_NODES;
  4304. ggml_tensor_extra_gpu * extra = &temp_tensor_extras[alloc_index];
  4305. extra->reset();
  4306. return extra;
  4307. }
  4308. };
  4309. GGML_CALL static const char * ggml_backend_vk_buffer_get_name(ggml_backend_buffer_t buffer) {
  4310. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4311. return ctx->name.c_str();
  4312. }
  4313. GGML_CALL static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  4314. return buffer->iface.get_name == ggml_backend_vk_buffer_get_name;
  4315. }
  4316. GGML_CALL static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  4317. #ifdef GGML_VULKAN_DEBUG
  4318. std::cerr << "ggml_backend_vk_buffer_free_buffer()" << std::endl;
  4319. #endif
  4320. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4321. ggml_vk_destroy_buffer(ctx->dev_buffer);
  4322. delete ctx;
  4323. }
  4324. GGML_CALL static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  4325. return vk_ptr_base;
  4326. UNUSED(buffer);
  4327. }
  4328. GGML_CALL static void ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  4329. #ifdef GGML_VULKAN_DEBUG
  4330. std::cerr << "ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")" << std::endl;
  4331. #endif
  4332. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4333. ggml_tensor_extra_gpu * extra = ctx->ggml_vk_alloc_temp_tensor_extra();
  4334. if (tensor->view_src != nullptr && tensor->view_src->extra != nullptr) {
  4335. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  4336. ggml_tensor_extra_gpu * extra_view = (ggml_tensor_extra_gpu *) tensor->view_src->extra;
  4337. extra->buffer_gpu = extra_view->buffer_gpu;
  4338. extra->offset = extra_view->offset + tensor->view_offs;
  4339. } else {
  4340. extra->buffer_gpu = ctx->dev_buffer;
  4341. extra->offset = (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  4342. }
  4343. tensor->backend = GGML_BACKEND_TYPE_GPU;
  4344. tensor->extra = extra;
  4345. }
  4346. GGML_CALL 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) {
  4347. #ifdef GGML_VULKAN_DEBUG
  4348. std::cerr << "ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")" << std::endl;
  4349. #endif
  4350. GGML_ASSERT(tensor->backend == GGML_BACKEND_TYPE_GPU);
  4351. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4352. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4353. vk_buffer buf = extra->buffer_gpu.lock();
  4354. ggml_vk_buffer_write(ctx->ctx, buf, extra->offset + offset, data, size);
  4355. }
  4356. GGML_CALL 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) {
  4357. #ifdef GGML_VULKAN_DEBUG
  4358. std::cerr << "ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")" << std::endl;
  4359. #endif
  4360. GGML_ASSERT(tensor->backend == GGML_BACKEND_TYPE_GPU);
  4361. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4362. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4363. vk_buffer buf = extra->buffer_gpu.lock();
  4364. ggml_vk_buffer_read(ctx->ctx, buf, extra->offset + offset, data, size);
  4365. }
  4366. GGML_CALL static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  4367. if (ggml_backend_buffer_is_vk(src->buffer)) {
  4368. ggml_tensor_extra_gpu * src_extra = (ggml_tensor_extra_gpu *) src->extra;
  4369. ggml_tensor_extra_gpu * dst_extra = (ggml_tensor_extra_gpu *) dst->extra;
  4370. vk_buffer src_buf = src_extra->buffer_gpu.lock();
  4371. vk_buffer dst_buf = dst_extra->buffer_gpu.lock();
  4372. ggml_vk_buffer_copy(dst_buf, dst_extra->offset, src_buf, src_extra->offset, ggml_nbytes(src));
  4373. return true;
  4374. }
  4375. return false;
  4376. UNUSED(buffer);
  4377. }
  4378. GGML_CALL static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  4379. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  4380. ggml_vk_buffer_memset(ctx->ctx, ctx->dev_buffer, 0, value, buffer->size);
  4381. }
  4382. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  4383. /* .get_name = */ ggml_backend_vk_buffer_get_name,
  4384. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  4385. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  4386. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  4387. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  4388. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  4389. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  4390. /* .clear = */ ggml_backend_vk_buffer_clear,
  4391. /* .reset = */ NULL,
  4392. };
  4393. // vk buffer type
  4394. struct ggml_backend_vk_buffer_type_context {
  4395. std::string name;
  4396. ggml_backend_vk_context * ctx;
  4397. };
  4398. GGML_CALL static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  4399. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  4400. return ctx->name.c_str();
  4401. }
  4402. GGML_CALL static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  4403. #ifdef GGML_VULKAN_DEBUG
  4404. std::cerr << "ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")" << std::endl;
  4405. #endif
  4406. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  4407. vk_buffer dev_buffer = ggml_vk_create_buffer_device(ctx->ctx, size);
  4408. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->ctx, std::move(dev_buffer), ctx->name);
  4409. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  4410. }
  4411. GGML_CALL static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  4412. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  4413. return ctx->ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  4414. }
  4415. GGML_CALL static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  4416. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  4417. return ctx->ctx->device->max_memory_allocation_size;
  4418. }
  4419. GGML_CALL static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  4420. return ggml_nbytes(tensor);
  4421. UNUSED(buft);
  4422. }
  4423. GGML_CALL static bool ggml_backend_vk_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) {
  4424. if (!ggml_backend_is_vk(backend)) {
  4425. return false;
  4426. }
  4427. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  4428. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4429. return buft_ctx->ctx->idx == ctx->idx;
  4430. }
  4431. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  4432. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  4433. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  4434. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  4435. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  4436. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  4437. /* .supports_backend = */ ggml_backend_vk_buffer_type_supports_backend,
  4438. /* .is_host = */ NULL,
  4439. };
  4440. GGML_CALL ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t idx) {
  4441. #ifdef GGML_VULKAN_DEBUG
  4442. std::cerr << "ggml_backend_vk_buffer_type(" << idx << ")" << std::endl;
  4443. #endif
  4444. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4445. ggml_backend_vk_init(idx);
  4446. return &vk_instance.buffer_types[idx];
  4447. }
  4448. // host buffer type
  4449. GGML_CALL static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  4450. return GGML_VK_NAME "_Host";
  4451. UNUSED(buft);
  4452. }
  4453. GGML_CALL static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  4454. return GGML_VK_NAME "_Host";
  4455. UNUSED(buffer);
  4456. }
  4457. GGML_CALL static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  4458. #ifdef GGML_VULKAN_DEBUG
  4459. std::cerr << "ggml_backend_vk_host_buffer_free_buffer()" << std::endl;
  4460. #endif
  4461. ggml_vk_host_free(&vk_instance.contexts[0], buffer->context);
  4462. }
  4463. GGML_CALL static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  4464. #ifdef GGML_VULKAN_DEBUG
  4465. std::cerr << "ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")" << std::endl;
  4466. #endif
  4467. void * ptr = nullptr;
  4468. try {
  4469. ptr = ggml_vk_host_malloc(&vk_instance.contexts[0], size);
  4470. } catch (vk::SystemError& e) {
  4471. std::cerr << "ggml_vulkan: Failed to allocate pinned memory." << std::endl;
  4472. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  4473. // fallback to cpu buffer
  4474. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  4475. }
  4476. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  4477. buffer->buft = buft;
  4478. buffer->iface.get_name = ggml_backend_vk_host_buffer_name;
  4479. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  4480. return buffer;
  4481. }
  4482. GGML_CALL static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  4483. return vk_instance.contexts[0].device->properties.limits.minMemoryMapAlignment;
  4484. UNUSED(buft);
  4485. }
  4486. GGML_CALL ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  4487. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  4488. /* .iface = */ {
  4489. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  4490. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  4491. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  4492. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  4493. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  4494. /* .supports_backend = */ ggml_backend_cpu_buffer_type()->iface.supports_backend,
  4495. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  4496. },
  4497. /* .context = */ nullptr,
  4498. };
  4499. if (!vk_instance.contexts[0].initialized) {
  4500. // Fall back to CPU
  4501. return ggml_backend_cpu_buffer_type();
  4502. }
  4503. return &ggml_backend_vk_buffer_type_host;
  4504. }
  4505. // backend
  4506. GGML_CALL static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  4507. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4508. return ctx->name.c_str();
  4509. }
  4510. GGML_CALL static void ggml_backend_vk_free(ggml_backend_t backend) {
  4511. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4512. #ifdef GGML_VULKAN_DEBUG
  4513. std::cerr << "ggml_backend_vk_free(" << ctx->name << ")" << std::endl;
  4514. #endif
  4515. size_t idx = ctx->idx;
  4516. ggml_vk_cleanup(ctx);
  4517. ctx->device.reset();
  4518. ctx->initialized = false;
  4519. vk_instance.initialized[idx] = false;
  4520. vk_instance.backends[idx] = nullptr;
  4521. memset(&vk_instance.buffer_types[idx], 0, sizeof(ggml_backend_buffer_type));
  4522. delete backend;
  4523. }
  4524. GGML_CALL static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  4525. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4526. GGML_ASSERT(ctx->initialized);
  4527. return ggml_backend_vk_buffer_type(ctx->idx);
  4528. }
  4529. GGML_CALL static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  4530. #ifdef GGML_VULKAN_DEBUG
  4531. std::cerr << "ggml_backend_vk_set_tensor_async(" << size << ")" << std::endl;
  4532. #endif
  4533. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4534. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_buffer_type(ctx->idx) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  4535. GGML_ASSERT(tensor->backend == GGML_BACKEND_TYPE_GPU);
  4536. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4537. if (ctx->transfer_ctx == nullptr) {
  4538. // Initialize new transfer context
  4539. ctx->transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  4540. ggml_vk_ctx_begin(ctx, ctx->transfer_ctx);
  4541. }
  4542. vk_buffer buf = extra->buffer_gpu.lock();
  4543. ggml_vk_buffer_write_async(ctx, ctx->transfer_ctx, buf, extra->offset + offset, data, size);
  4544. }
  4545. GGML_CALL static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  4546. #ifdef GGML_VULKAN_DEBUG
  4547. std::cerr << "ggml_backend_vk_get_tensor_async(" << size << ")" << std::endl;
  4548. #endif
  4549. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4550. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_buffer_type(ctx->idx) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  4551. GGML_ASSERT(tensor->backend == GGML_BACKEND_TYPE_GPU);
  4552. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4553. if (ctx->transfer_ctx == nullptr) {
  4554. // Initialize new transfer context
  4555. ctx->transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  4556. ggml_vk_ctx_begin(ctx, ctx->transfer_ctx);
  4557. }
  4558. vk_buffer buf = extra->buffer_gpu.lock();
  4559. ggml_vk_buffer_read_async(ctx, ctx->transfer_ctx, buf, extra->offset + offset, data, size);
  4560. }
  4561. GGML_CALL static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  4562. #ifdef GGML_VULKAN_DEBUG
  4563. std::cerr << "ggml_backend_vk_cpy_tensor_async()" << std::endl;
  4564. #endif
  4565. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4566. if ((dst->buffer->buft == ggml_backend_vk_buffer_type(ctx->idx) || dst->buffer->buft == ggml_backend_vk_host_buffer_type()) && ggml_backend_buffer_is_vk(src->buffer)) {
  4567. ggml_tensor_extra_gpu * src_extra = (ggml_tensor_extra_gpu *) src->extra;
  4568. ggml_tensor_extra_gpu * dst_extra = (ggml_tensor_extra_gpu *) dst->extra;
  4569. if (ctx->transfer_ctx == nullptr) {
  4570. // Initialize new transfer context
  4571. ctx->transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  4572. ggml_vk_ctx_begin(ctx, ctx->transfer_ctx);
  4573. }
  4574. vk_buffer src_buf = src_extra->buffer_gpu.lock();
  4575. vk_buffer dst_buf = dst_extra->buffer_gpu.lock();
  4576. ggml_vk_buffer_copy_async(ctx->transfer_ctx, src_buf, src_extra->offset, dst_buf, dst_extra->offset, ggml_nbytes(src));
  4577. return true;
  4578. }
  4579. return false;
  4580. }
  4581. GGML_CALL static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  4582. #ifdef GGML_VULKAN_DEBUG
  4583. std::cerr << "ggml_backend_vk_synchronize()" << std::endl;
  4584. #endif
  4585. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4586. if(ctx->transfer_ctx == nullptr) {
  4587. return;
  4588. }
  4589. ggml_vk_ctx_end(ctx->transfer_ctx);
  4590. for (auto& cpy : ctx->transfer_ctx->in_memcpys) {
  4591. memcpy(cpy.dst, cpy.src, cpy.n);
  4592. }
  4593. ggml_vk_submit(ctx->transfer_ctx, ctx->fence);
  4594. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_backend_vk_synchronize waitForFences");
  4595. ctx->device->device.resetFences({ ctx->fence });
  4596. for (auto& cpy : ctx->transfer_ctx->out_memcpys) {
  4597. memcpy(cpy.dst, cpy.src, cpy.n);
  4598. }
  4599. ctx->transfer_ctx = nullptr;
  4600. }
  4601. GGML_CALL static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  4602. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  4603. for (int i = 0; i < cgraph->n_nodes; i++) {
  4604. ggml_vk_preallocate_buffers_graph(ctx, cgraph->nodes[i]);
  4605. }
  4606. ggml_vk_preallocate_buffers(ctx);
  4607. int last_node = cgraph->n_nodes - 1;
  4608. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  4609. while (last_node > 0 && cgraph->nodes[last_node]->backend != GGML_BACKEND_TYPE_GPU) {
  4610. last_node -= 1;
  4611. }
  4612. for (int i = 0; i < cgraph->n_nodes; i++) {
  4613. ggml_vk_build_graph(ctx,cgraph->nodes[i], i == last_node);
  4614. }
  4615. ggml_compute_params params = {};
  4616. params.type = GGML_TASK_TYPE_COMPUTE;
  4617. params.ith = 0;
  4618. for (int i = 0; i < cgraph->n_nodes; i++) {
  4619. ggml_tensor * node = cgraph->nodes[i];
  4620. if (node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_NONE) {
  4621. continue;
  4622. }
  4623. bool ok = ggml_vk_compute_forward(ctx, &params, node);
  4624. if (!ok) {
  4625. fprintf(stderr, "%s: error: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op));
  4626. }
  4627. #ifdef GGML_VULKAN_CHECK_RESULTS
  4628. else {
  4629. ggml_vk_check_results_1(ctx, &params, node);
  4630. }
  4631. #endif
  4632. GGML_ASSERT(ok);
  4633. }
  4634. ggml_vk_graph_cleanup(ctx);
  4635. return GGML_STATUS_SUCCESS;
  4636. UNUSED(backend);
  4637. }
  4638. GGML_CALL static bool ggml_backend_vk_supports_op(ggml_backend_t backend, const ggml_tensor * op) {
  4639. switch (op->op) {
  4640. case GGML_OP_UNARY:
  4641. switch (ggml_get_unary_op(op)) {
  4642. case GGML_UNARY_OP_GELU:
  4643. case GGML_UNARY_OP_SILU:
  4644. case GGML_UNARY_OP_RELU:
  4645. return true;
  4646. default:
  4647. return false;
  4648. }
  4649. break;
  4650. case GGML_OP_MUL_MAT:
  4651. case GGML_OP_MUL_MAT_ID:
  4652. {
  4653. struct ggml_tensor * a;
  4654. struct ggml_tensor * b;
  4655. if (op->op == GGML_OP_MUL_MAT) {
  4656. a = op->src[0];
  4657. b = op->src[1];
  4658. } else {
  4659. a = op->src[2];
  4660. b = op->src[1];
  4661. }
  4662. if (a->ne[3] != b->ne[3]) {
  4663. return false;
  4664. }
  4665. return true;
  4666. } break;
  4667. // case GGML_OP_GET_ROWS:
  4668. // {
  4669. // switch (op->src[0]->type) {
  4670. // case GGML_TYPE_F16:
  4671. // case GGML_TYPE_F32:
  4672. // case GGML_TYPE_Q4_0:
  4673. // case GGML_TYPE_Q4_1:
  4674. // case GGML_TYPE_Q5_0:
  4675. // case GGML_TYPE_Q5_1:
  4676. // case GGML_TYPE_Q8_0:
  4677. // return true;
  4678. // default:
  4679. // return false;
  4680. // }
  4681. // } break;
  4682. case GGML_OP_CPY:
  4683. {
  4684. ggml_type src0_type = op->src[0]->type;
  4685. ggml_type src1_type = op->src[1]->type;
  4686. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4687. return true;
  4688. }
  4689. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4690. return true;
  4691. }
  4692. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4693. return true;
  4694. }
  4695. return false;
  4696. } break;
  4697. case GGML_OP_DUP:
  4698. // case GGML_OP_REPEAT:
  4699. // {
  4700. // ggml_type src0_type = op->src[0]->type;
  4701. // return src0_type != GGML_TYPE_I32 && src0_type != GGML_TYPE_I16;
  4702. // } break;
  4703. case GGML_OP_ROPE:
  4704. {
  4705. const int mode = ((const int32_t *) op->op_params)[2];
  4706. const bool is_glm = mode & 4;
  4707. return !is_glm;
  4708. } break;
  4709. case GGML_OP_NONE:
  4710. case GGML_OP_RESHAPE:
  4711. case GGML_OP_VIEW:
  4712. case GGML_OP_PERMUTE:
  4713. case GGML_OP_TRANSPOSE:
  4714. case GGML_OP_NORM:
  4715. case GGML_OP_ADD:
  4716. case GGML_OP_MUL:
  4717. case GGML_OP_RMS_NORM:
  4718. case GGML_OP_SCALE:
  4719. case GGML_OP_SQR:
  4720. case GGML_OP_CLAMP:
  4721. case GGML_OP_CONT:
  4722. case GGML_OP_DIAG_MASK_INF:
  4723. case GGML_OP_SOFT_MAX:
  4724. case GGML_OP_ARGSORT:
  4725. return true;
  4726. default:
  4727. return false;
  4728. }
  4729. UNUSED(backend);
  4730. }
  4731. // TODO: enable async and synchronize
  4732. static ggml_backend_i ggml_backend_vk_interface = {
  4733. /* .get_name = */ ggml_backend_vk_name,
  4734. /* .free = */ ggml_backend_vk_free,
  4735. /* .get_default_buffer_type = */ ggml_backend_vk_get_default_buffer_type,
  4736. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  4737. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  4738. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  4739. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  4740. /* .graph_plan_create = */ NULL,
  4741. /* .graph_plan_free = */ NULL,
  4742. /* .graph_plan_compute = */ NULL,
  4743. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  4744. /* .supports_op = */ ggml_backend_vk_supports_op,
  4745. /* .event_new = */ NULL,
  4746. /* .event_free = */ NULL,
  4747. /* .event_record = */ NULL,
  4748. /* .event_wait = */ NULL,
  4749. /* .event_synchronize = */ NULL,
  4750. };
  4751. static ggml_guid_t ggml_backend_vk_guid() {
  4752. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  4753. return &guid;
  4754. }
  4755. GGML_CALL ggml_backend_t ggml_backend_vk_init(size_t idx) {
  4756. if (vk_instance.initialized[idx]) {
  4757. return vk_instance.backends[idx];
  4758. }
  4759. #ifdef GGML_VULKAN_DEBUG
  4760. std::cerr << "ggml_backend_vk_init(" << idx << ")" << std::endl;
  4761. #endif
  4762. ggml_backend_vk_context * ctx = &vk_instance.contexts[idx];
  4763. ggml_vk_init(ctx, idx);
  4764. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4765. vk_instance.buffer_types[idx] = {
  4766. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4767. /* .context = */ new ggml_backend_vk_buffer_type_context{ ctx->name, ctx },
  4768. };
  4769. vk_instance.initialized[idx] = true;
  4770. ggml_backend_t vk_backend = new ggml_backend {
  4771. /* .guid = */ ggml_backend_vk_guid(),
  4772. /* .interface = */ ggml_backend_vk_interface,
  4773. /* .context = */ &vk_instance.contexts[ctx->idx],
  4774. };
  4775. vk_instance.backends[idx] = vk_backend;
  4776. return vk_backend;
  4777. }
  4778. GGML_CALL bool ggml_backend_is_vk(ggml_backend_t backend) {
  4779. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  4780. }
  4781. GGML_CALL int ggml_backend_vk_get_device_count() {
  4782. return ggml_vk_get_device_count();
  4783. }
  4784. GGML_CALL void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  4785. ggml_vk_get_device_description(device, description, description_size);
  4786. }
  4787. GGML_CALL void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  4788. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  4789. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  4790. vk::PhysicalDeviceMemoryProperties memprops = vkdev.getMemoryProperties();
  4791. for (const vk::MemoryHeap& heap : memprops.memoryHeaps) {
  4792. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  4793. *total = heap.size;
  4794. *free = heap.size;
  4795. break;
  4796. }
  4797. }
  4798. }
  4799. // backend registry
  4800. GGML_CALL static ggml_backend_t ggml_backend_reg_vk_init(const char * params, void * user_data) {
  4801. ggml_backend_t vk_backend = ggml_backend_vk_init((int) (intptr_t) user_data);
  4802. return vk_backend;
  4803. UNUSED(params);
  4804. }
  4805. extern "C" GGML_CALL int ggml_backend_vk_reg_devices();
  4806. GGML_CALL int ggml_backend_vk_reg_devices() {
  4807. for (auto idx : vk_instance.device_indices) {
  4808. char name[128];
  4809. snprintf(name, sizeof(name), "%s%ld", GGML_VK_NAME, idx);
  4810. ggml_backend_register(name, ggml_backend_reg_vk_init, ggml_backend_vk_buffer_type(idx), (void *) (intptr_t) idx);
  4811. }
  4812. return vk_instance.device_indices.size();
  4813. }
  4814. // Extension availability
  4815. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  4816. #ifdef GGML_VULKAN_VALIDATE
  4817. bool portability_enumeration_ext = false;
  4818. // Check for portability enumeration extension for MoltenVK support
  4819. for (const auto& properties : instance_extensions) {
  4820. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  4821. return true;
  4822. }
  4823. }
  4824. if (!portability_enumeration_ext) {
  4825. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  4826. }
  4827. #endif
  4828. return false;
  4829. UNUSED(instance_extensions);
  4830. }
  4831. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  4832. #ifdef __APPLE__
  4833. bool portability_enumeration_ext = false;
  4834. // Check for portability enumeration extension for MoltenVK support
  4835. for (const auto& properties : instance_extensions) {
  4836. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  4837. return true;
  4838. }
  4839. }
  4840. if (!portability_enumeration_ext) {
  4841. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  4842. }
  4843. #endif
  4844. return false;
  4845. UNUSED(instance_extensions);
  4846. }
  4847. // checks
  4848. #ifdef GGML_VULKAN_CHECK_RESULTS
  4849. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  4850. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  4851. return;
  4852. }
  4853. for (int j = 0; j < level; j++) {
  4854. std::cerr << " ";
  4855. }
  4856. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << " backend=" << tensor->backend << std::endl;
  4857. done.push_back(tensor);
  4858. for (int i = 0; i < GGML_MAX_SRC; i++) {
  4859. if (tensor->src[i] != nullptr) {
  4860. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  4861. }
  4862. }
  4863. }
  4864. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  4865. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  4866. return;
  4867. }
  4868. i0 = std::max(i0, 5);
  4869. i1 = std::max(i1, 5);
  4870. i2 = std::max(i2, 0);
  4871. i3 = std::max(i3, 0);
  4872. fprintf(stderr, " ");
  4873. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  4874. fprintf(stderr, "%7d ", idx1);
  4875. }
  4876. fprintf(stderr, "\n");
  4877. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  4878. fprintf(stderr, "%7d: ", idx0);
  4879. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  4880. 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]) {
  4881. float val;
  4882. if (tensor->type == GGML_TYPE_F32) {
  4883. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  4884. } else if (tensor->type == GGML_TYPE_F16) {
  4885. 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]));
  4886. }
  4887. fprintf(stderr, "% 7.2f ", val);
  4888. } else {
  4889. fprintf(stderr, " ");
  4890. }
  4891. }
  4892. fprintf(stderr, "\n");
  4893. }
  4894. }
  4895. static void ggml_vk_print_tensor(ggml_backend_vk_context * ctx, const ggml_tensor * tensor, const char * name) {
  4896. void * tensor_data = tensor->data;
  4897. if (tensor->backend == GGML_BACKEND_TYPE_GPU) {
  4898. const size_t tensor_size = ggml_nbytes(tensor);
  4899. tensor_data = malloc(tensor_size);
  4900. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  4901. vk_buffer buffer_gpu = extra->buffer_gpu.lock();
  4902. ggml_vk_buffer_read(ctx, buffer_gpu, extra->offset, tensor_data, tensor_size);
  4903. }
  4904. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  4905. std::cerr << "tensor=" << tensor << " tensor->backend: " << tensor->backend << " 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;
  4906. if (tensor->src[0] != nullptr) {
  4907. 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) << " backend=" << tensor->src[0]->backend << " 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;
  4908. }
  4909. if (tensor->src[1] != nullptr) {
  4910. 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) << " backend=" << tensor->src[1]->backend << " 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;
  4911. }
  4912. std::cerr << std::endl << "Result:" << std::endl;
  4913. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  4914. std::cerr << std::endl;
  4915. std::cerr << std::endl << "Result:" << std::endl;
  4916. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 1, 0);
  4917. std::cerr << std::endl;
  4918. std::vector<const ggml_tensor *> done;
  4919. ggml_vk_print_graph_origin(tensor, done);
  4920. if (tensor->backend == GGML_BACKEND_TYPE_GPU) {
  4921. free(tensor_data);
  4922. }
  4923. }
  4924. static void ggml_vk_check_tensor(const std::string& name, const ggml_tensor * tensor) {
  4925. return;
  4926. GGML_ASSERT(tensor->backend == GGML_BACKEND_TYPE_CPU);
  4927. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  4928. return;
  4929. }
  4930. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  4931. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  4932. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  4933. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  4934. float val = 0.0f;
  4935. if (tensor->type == GGML_TYPE_F32) {
  4936. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  4937. } else if (tensor->type == GGML_TYPE_F16) {
  4938. val = 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]));
  4939. }
  4940. if (std::isnan(val)) {
  4941. std::cerr << "ERROR: TENSOR CHECK " << name << ": Invalid value in " << ggml_op_name(tensor->op) << " i3=" << i3 << " i2=" << i2 << " i1=" << i1 << " i0=" << i0 << " val=" << val << std::endl;
  4942. std::cerr << "tensor=" << tensor << " tensor->type=" << ggml_type_name(tensor->type) << " tensor->backend: " << tensor->backend << " 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;
  4943. std::cerr << std::endl;
  4944. ggml_vk_print_tensor_area(tensor, tensor->data, i0, i1, i2, i3);
  4945. std::cerr << std::endl;
  4946. std::vector<const ggml_tensor *> done;
  4947. ggml_vk_print_graph_origin(tensor, done);
  4948. GGML_ASSERT(false);
  4949. }
  4950. }
  4951. }
  4952. }
  4953. }
  4954. }
  4955. void * comp_result;
  4956. size_t comp_size;
  4957. size_t comp_nb[GGML_MAX_DIMS];
  4958. size_t check_counter = 0;
  4959. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor) {
  4960. if (params->ith != 0) {
  4961. return;
  4962. }
  4963. if (params->type == GGML_TASK_TYPE_INIT || params->type == GGML_TASK_TYPE_FINALIZE || tensor->op == GGML_OP_TRANSPOSE) {
  4964. return;
  4965. }
  4966. check_counter++;
  4967. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  4968. return;
  4969. }
  4970. ggml_tensor * src0 = tensor->src[0];
  4971. ggml_tensor * src1 = tensor->src[1];
  4972. ggml_tensor * src2 = tensor->src[2];
  4973. struct ggml_init_params iparams = {
  4974. /*.mem_size =*/ 1024*1024*1024,
  4975. /*.mem_buffer =*/ NULL,
  4976. /*.no_alloc =*/ false,
  4977. };
  4978. struct ggml_context * ggml_ctx = ggml_init(iparams);
  4979. struct ggml_tensor * src0_clone = nullptr;
  4980. struct ggml_tensor * src1_clone = nullptr;
  4981. struct ggml_tensor * src2_clone = nullptr;
  4982. struct ggml_tensor * tensor_clone = nullptr;
  4983. size_t src0_size;
  4984. size_t src1_size;
  4985. size_t src2_size;
  4986. void * src0_buffer;
  4987. void * src1_buffer;
  4988. void * src2_buffer;
  4989. if (src0 != nullptr) {
  4990. src0_clone = ggml_dup_tensor(ggml_ctx, src0);
  4991. src0_size = ggml_nbytes(src0);
  4992. src0_buffer = malloc(src0_size);
  4993. src0_clone->data = src0_buffer;
  4994. if (src0->backend == GGML_BACKEND_TYPE_CPU) {
  4995. memcpy(src0_clone->data, src0->data, src0_size);
  4996. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  4997. } else if (src0->backend == GGML_BACKEND_TYPE_GPU) {
  4998. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) src0->extra;
  4999. vk_buffer buffer_gpu = extra->buffer_gpu.lock();
  5000. uint64_t offset = extra->offset;
  5001. if (!ggml_is_contiguous(src0) && ggml_vk_dim01_contiguous(src0)) {
  5002. for (int i3 = 0; i3 < src0->ne[3]; i3++) {
  5003. for (int i2 = 0; i2 < src0->ne[2]; i2++) {
  5004. const int idx = i3*src0->ne[2] + i2;
  5005. ggml_vk_buffer_read(ctx, buffer_gpu, offset + idx * src0->nb[2], ((char *)src0_clone->data + idx * src0_clone->nb[2]), src0->ne[1] * src0->nb[1]);
  5006. }
  5007. }
  5008. src0_clone->nb[0] = src0->nb[0];
  5009. src0_clone->nb[1] = src0->nb[1];
  5010. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  5011. src0_clone->nb[i] = src0_clone->nb[i - 1]*src0_clone->ne[i - 1];
  5012. }
  5013. } else {
  5014. if (offset + src0_size >= buffer_gpu->size) {
  5015. src0_size = buffer_gpu->size - offset;
  5016. }
  5017. ggml_vk_buffer_read(ctx, buffer_gpu, offset, src0_clone->data, src0_size);
  5018. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  5019. }
  5020. } else {
  5021. GGML_ASSERT(false);
  5022. }
  5023. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  5024. ggml_vk_print_tensor(ctx, src0, "src0");
  5025. }
  5026. ggml_vk_check_tensor(std::string(ggml_op_name(tensor->op)) + "->src0", src0_clone);
  5027. }
  5028. if (src1 != nullptr) {
  5029. src1_clone = ggml_dup_tensor(ggml_ctx, src1);
  5030. src1_size = ggml_nbytes(src1);
  5031. src1_buffer = malloc(src1_size);
  5032. src1_clone->data = src1_buffer;
  5033. if (src1->backend == GGML_BACKEND_TYPE_CPU) {
  5034. memcpy(src1_clone->data, src1->data, src1_size);
  5035. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  5036. } else if (src1->backend == GGML_BACKEND_TYPE_GPU) {
  5037. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) src1->extra;
  5038. vk_buffer buffer_gpu = extra->buffer_gpu.lock();
  5039. uint64_t offset = extra->offset;
  5040. if (!ggml_is_contiguous(src1) && ggml_vk_dim01_contiguous(src1)) {
  5041. for (int i3 = 0; i3 < src1->ne[3]; i3++) {
  5042. for (int i2 = 0; i2 < src1->ne[2]; i2++) {
  5043. const int idx = i3*src1->ne[2] + i2;
  5044. ggml_vk_buffer_read(ctx, buffer_gpu, offset + idx * src1->nb[2], ((char *)src1_clone->data + idx * src1_clone->nb[2]), src1->ne[1] * src1->nb[1]);
  5045. }
  5046. }
  5047. src1_clone->nb[0] = src1->nb[0];
  5048. src1_clone->nb[1] = src1->nb[1];
  5049. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  5050. src1_clone->nb[i] = src1_clone->nb[i - 1]*src1_clone->ne[i - 1];
  5051. }
  5052. } else {
  5053. if (offset + src1_size >= buffer_gpu->size) {
  5054. src1_size = buffer_gpu->size - offset;
  5055. }
  5056. ggml_vk_buffer_read(ctx, buffer_gpu, offset, src1_clone->data, src1_size);
  5057. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  5058. }
  5059. } else {
  5060. GGML_ASSERT(false);
  5061. }
  5062. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  5063. ggml_vk_print_tensor(ctx, src1, "src1");
  5064. std::cerr << "TENSOR CHECK: " << ggml_op_name(src1_clone->op) << " (check " << check_counter << ")" << std::endl;
  5065. std::cerr << "src1_clone=" << tensor << " src1_clone->backend: " << src1_clone->backend << " src1_clone->type: " << ggml_type_name(src1_clone->type) << " ne0=" << src1_clone->ne[0] << " nb0=" << src1_clone->nb[0] << " ne1=" << src1_clone->ne[1] << " nb1=" << src1_clone->nb[1] << " ne2=" << src1_clone->ne[2] << " nb2=" << src1_clone->nb[2] << " ne3=" << src1_clone->ne[3] << " nb3=" << src1_clone->nb[3] << std::endl;
  5066. if (src1->src[0] != nullptr) {
  5067. std::cerr << "src1->src[0]=" << src1->src[0] << " op=" << ggml_op_name(src1->src[0]->op) << " type=" << ggml_type_name(src1->src[0]->type) << " backend=" << src1->src[0]->backend << " ne0=" << src1->src[0]->ne[0] << " nb0=" << src1->src[0]->nb[0] << " ne1=" << src1->src[0]->ne[1] << " nb1=" << src1->src[0]->nb[1] << " ne2=" << src1->src[0]->ne[2] << " nb2=" << src1->src[0]->nb[2] << " ne3=" << src1->src[0]->ne[3] << " nb3=" << src1->src[0]->nb[3] << std::endl;
  5068. }
  5069. if (src1->src[1] != nullptr) {
  5070. std::cerr << "src1->src[1]=" << src1->src[1] << " op=" << ggml_op_name(src1->src[1]->op) << " type=" << ggml_type_name(src1->src[1]->type) << " backend=" << src1->src[1]->backend << " ne0=" << src1->src[1]->ne[0] << " nb0=" << src1->src[1]->nb[0] << " ne1=" << src1->src[1]->ne[1] << " nb1=" << src1->src[1]->nb[1] << " ne2=" << src1->src[1]->ne[2] << " nb2=" << src1->src[1]->nb[2] << " ne3=" << src1->src[1]->ne[3] << " nb3=" << src1->src[1]->nb[3] << std::endl;
  5071. }
  5072. std::cerr << std::endl << "Result:" << std::endl;
  5073. ggml_vk_print_tensor_area(src1_clone, src1_clone->data, 5, 5, 0, 0);
  5074. std::cerr << std::endl;
  5075. std::cerr << std::endl << "Result:" << std::endl;
  5076. ggml_vk_print_tensor_area(src1_clone, src1_clone->data, 5, 5, 1, 0);
  5077. std::cerr << std::endl;
  5078. std::vector<const ggml_tensor *> done;
  5079. ggml_vk_print_graph_origin(src1_clone, done);
  5080. }
  5081. ggml_vk_check_tensor(std::string(ggml_op_name(tensor->op)) + "->src1", src1_clone);
  5082. }
  5083. if (src2 != nullptr) {
  5084. src2_clone = ggml_dup_tensor(ggml_ctx, src2);
  5085. src2_size = ggml_nbytes(src2);
  5086. src2_buffer = malloc(src2_size);
  5087. src2_clone->data = src2_buffer;
  5088. if (src2->backend == GGML_BACKEND_TYPE_CPU) {
  5089. memcpy(src2_clone->data, src2->data, src2_size);
  5090. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  5091. } else if (src2->backend == GGML_BACKEND_TYPE_GPU) {
  5092. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) src2->extra;
  5093. vk_buffer buf = extra->buffer_gpu.lock();
  5094. uint64_t offset = extra->offset;
  5095. if (!ggml_is_contiguous(src2) && ggml_vk_dim01_contiguous(src2)) {
  5096. for (int i3 = 0; i3 < src2->ne[3]; i3++) {
  5097. for (int i2 = 0; i2 < src2->ne[2]; i2++) {
  5098. const int idx = i3*src2->ne[2] + i2;
  5099. ggml_vk_buffer_read(ctx, buf, offset + idx * src2->nb[2], ((char *)src2_clone->data + idx * src2_clone->nb[2]), src2->ne[1] * src2->nb[1]);
  5100. }
  5101. }
  5102. src2_clone->nb[0] = src2->nb[0];
  5103. src2_clone->nb[1] = src2->nb[1];
  5104. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  5105. src2_clone->nb[i] = src2_clone->nb[i - 1]*src2_clone->ne[i - 1];
  5106. }
  5107. } else {
  5108. if (offset + src2_size >= buf->size) {
  5109. src2_size = buf->size - offset;
  5110. }
  5111. ggml_vk_buffer_read(ctx, buf, offset, src2_clone->data, src2_size);
  5112. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  5113. }
  5114. } else {
  5115. GGML_ASSERT(false);
  5116. }
  5117. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  5118. ggml_vk_print_tensor(ctx, src2, "src2");
  5119. std::cerr << "TENSOR CHECK: " << ggml_op_name(src2_clone->op) << " (check " << check_counter << ")" << std::endl;
  5120. std::cerr << "src2_clone=" << tensor << " src2_clone->backend: " << src2_clone->backend << " src2_clone->type: " << ggml_type_name(src2_clone->type) << " ne0=" << src2_clone->ne[0] << " nb0=" << src2_clone->nb[0] << " ne1=" << src2_clone->ne[1] << " nb1=" << src2_clone->nb[1] << " ne2=" << src2_clone->ne[2] << " nb2=" << src2_clone->nb[2] << " ne3=" << src2_clone->ne[3] << " nb3=" << src2_clone->nb[3] << std::endl;
  5121. if (src2->src[0] != nullptr) {
  5122. std::cerr << "src2->src[0]=" << src2->src[0] << " op=" << ggml_op_name(src2->src[0]->op) << " type=" << ggml_type_name(src2->src[0]->type) << " backend=" << src2->src[0]->backend << " ne0=" << src2->src[0]->ne[0] << " nb0=" << src2->src[0]->nb[0] << " ne1=" << src2->src[0]->ne[1] << " nb1=" << src2->src[0]->nb[1] << " ne2=" << src2->src[0]->ne[2] << " nb2=" << src2->src[0]->nb[2] << " ne3=" << src2->src[0]->ne[3] << " nb3=" << src2->src[0]->nb[3] << std::endl;
  5123. }
  5124. if (src2->src[1] != nullptr) {
  5125. std::cerr << "src2->src[1]=" << src2->src[1] << " op=" << ggml_op_name(src2->src[1]->op) << " type=" << ggml_type_name(src2->src[1]->type) << " backend=" << src2->src[1]->backend << " ne0=" << src2->src[1]->ne[0] << " nb0=" << src2->src[1]->nb[0] << " ne1=" << src2->src[1]->ne[1] << " nb1=" << src2->src[1]->nb[1] << " ne2=" << src2->src[1]->ne[2] << " nb2=" << src2->src[1]->nb[2] << " ne3=" << src2->src[1]->ne[3] << " nb3=" << src2->src[1]->nb[3] << std::endl;
  5126. }
  5127. std::cerr << std::endl << "Result:" << std::endl;
  5128. ggml_vk_print_tensor_area(src2_clone, src2_clone->data, 5, 5, 0, 0);
  5129. std::cerr << std::endl;
  5130. std::cerr << std::endl << "Result:" << std::endl;
  5131. ggml_vk_print_tensor_area(src2_clone, src2_clone->data, 5, 5, 1, 0);
  5132. std::cerr << std::endl;
  5133. std::vector<const ggml_tensor *> done;
  5134. ggml_vk_print_graph_origin(src2_clone, done);
  5135. }
  5136. ggml_vk_check_tensor(std::string(ggml_op_name(tensor->op)) + "->src2", src2_clone);
  5137. }
  5138. if (tensor->op == GGML_OP_MUL_MAT) {
  5139. tensor_clone = ggml_mul_mat(ggml_ctx, src0_clone, src1_clone);
  5140. } else if (tensor->op == GGML_OP_MUL) {
  5141. tensor_clone = ggml_mul(ggml_ctx, src0_clone, src1_clone);
  5142. } else if (tensor->op == GGML_OP_SCALE) {
  5143. tensor_clone = ggml_scale(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0]);
  5144. } else if (tensor->op == GGML_OP_SQR) {
  5145. tensor_clone = ggml_sqr(ggml_ctx, src0_clone);
  5146. } else if (tensor->op == GGML_OP_CLAMP) {
  5147. tensor_clone = ggml_clamp(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  5148. } else if (tensor->op == GGML_OP_ADD) {
  5149. tensor_clone = ggml_add(ggml_ctx, src0_clone, src1_clone);
  5150. } else if (tensor->op == GGML_OP_NORM) {
  5151. tensor_clone = ggml_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  5152. } else if (tensor->op == GGML_OP_RMS_NORM) {
  5153. tensor_clone = ggml_rms_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  5154. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  5155. if (src1 != nullptr) {
  5156. tensor_clone = ggml_soft_max_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  5157. } else {
  5158. tensor_clone = ggml_soft_max(ggml_ctx, src0_clone);
  5159. }
  5160. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  5161. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  5162. } else if (tensor->op == GGML_OP_ROPE) {
  5163. const int n_dims = ((int32_t *) tensor->op_params)[1];
  5164. const int mode = ((int32_t *) tensor->op_params)[2];
  5165. const int n_ggml_ctx = ((int32_t *) tensor->op_params)[3];
  5166. const int n_orig_ggml_ctx = ((int32_t *) tensor->op_params)[4];
  5167. float freq_base = ((float *) tensor->op_params)[5];
  5168. float freq_scale = ((float *) tensor->op_params)[6];
  5169. float ext_factor = ((float *) tensor->op_params)[7];
  5170. float attn_factor = ((float *) tensor->op_params)[8];
  5171. float beta_fast = ((float *) tensor->op_params)[9];
  5172. float beta_slow = ((float *) tensor->op_params)[10];
  5173. tensor_clone = ggml_rope_custom(ggml_ctx, src0_clone, src1_clone, n_dims, mode, n_ggml_ctx, n_orig_ggml_ctx, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  5174. } else if (tensor->op == GGML_OP_UNARY) {
  5175. switch (ggml_get_unary_op(tensor)) {
  5176. case GGML_UNARY_OP_SILU:
  5177. tensor_clone = ggml_silu(ggml_ctx, src0_clone);
  5178. break;
  5179. case GGML_UNARY_OP_GELU:
  5180. tensor_clone = ggml_gelu(ggml_ctx, src0_clone);
  5181. break;
  5182. case GGML_UNARY_OP_RELU:
  5183. tensor_clone = ggml_relu(ggml_ctx, src0_clone);
  5184. break;
  5185. default:
  5186. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  5187. GGML_ASSERT(false);
  5188. }
  5189. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  5190. if (src1 == nullptr) {
  5191. tensor_clone = ggml_dup(ggml_ctx, src0_clone);
  5192. tensor_clone->type = tensor->type;
  5193. } else {
  5194. tensor_clone = ggml_cpy(ggml_ctx, src0_clone, src1_clone);
  5195. }
  5196. } else if (tensor->op == GGML_OP_CONT) {
  5197. tensor_clone = ggml_cont_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  5198. } else if (tensor->op == GGML_OP_RESHAPE) {
  5199. tensor_clone = ggml_reshape_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  5200. } else if (tensor->op == GGML_OP_VIEW) {
  5201. tensor_clone = ggml_view_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], tensor->nb[1], tensor->nb[2], tensor->nb[3], ((int32_t *) tensor->op_params)[0]);
  5202. } else if (tensor->op == GGML_OP_PERMUTE) {
  5203. int32_t * params = (int32_t *)tensor->op_params;
  5204. tensor_clone = ggml_permute(ggml_ctx, src0_clone, params[0], params[1], params[2], params[3]);
  5205. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  5206. tensor_clone = ggml_transpose(ggml_ctx, src0_clone);
  5207. } else {
  5208. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  5209. GGML_ASSERT(false);
  5210. }
  5211. // Disable vulkan here to avoid the hooks in ggml.c
  5212. ctx->disable = true;
  5213. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5214. ggml_build_forward_expand(cgraph, tensor_clone);
  5215. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 8);
  5216. ctx->disable = false;
  5217. ggml_vk_check_tensor(ggml_op_name(tensor->op), tensor_clone);
  5218. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  5219. ggml_vk_print_tensor(ctx, tensor_clone, "tensor_clone");
  5220. }
  5221. comp_size = ggml_nbytes(tensor_clone);
  5222. comp_result = malloc(comp_size);
  5223. memcpy(comp_result, tensor_clone->data, comp_size);
  5224. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  5225. if (src0 != nullptr) {
  5226. free(src0_buffer);
  5227. }
  5228. if (src1 != nullptr) {
  5229. free(src1_buffer);
  5230. }
  5231. if (src2 != nullptr) {
  5232. free(src1_buffer);
  5233. }
  5234. ggml_free(ggml_ctx);
  5235. }
  5236. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_compute_params * params, ggml_tensor * tensor) {
  5237. if (params->ith != 0) {
  5238. return;
  5239. }
  5240. if (params->type == GGML_TASK_TYPE_INIT || params->type == GGML_TASK_TYPE_FINALIZE || tensor->op == GGML_OP_TRANSPOSE) {
  5241. return;
  5242. }
  5243. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  5244. return;
  5245. }
  5246. ggml_tensor * src0 = tensor->src[0];
  5247. ggml_tensor * src1 = tensor->src[1];
  5248. void * tensor_data = tensor->data;
  5249. if (tensor->backend == GGML_BACKEND_TYPE_GPU) {
  5250. size_t tensor_size = ggml_nbytes(tensor);
  5251. tensor_data = malloc(tensor_size);
  5252. ggml_tensor_extra_gpu * extra = (ggml_tensor_extra_gpu *) tensor->extra;
  5253. vk_buffer buffer_gpu = extra->buffer_gpu.lock();
  5254. if (extra->offset + tensor_size >= buffer_gpu->size) {
  5255. tensor_size = buffer_gpu->size - (extra->offset);
  5256. }
  5257. ggml_vk_buffer_read(ctx, buffer_gpu, extra->offset, tensor_data, tensor_size);
  5258. }
  5259. float first_error_result = -1.0f;
  5260. float first_error_correct = -1.0f;
  5261. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  5262. double avg_err = 0.0;
  5263. size_t counter = 0;
  5264. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  5265. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  5266. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  5267. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  5268. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  5269. float correct = 0.0f;
  5270. float result = 0.0f;
  5271. if (buffer_size_fit) {
  5272. if (tensor->type == GGML_TYPE_F32) {
  5273. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  5274. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  5275. } else if (tensor->type == GGML_TYPE_F16) {
  5276. 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]));
  5277. 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]));
  5278. } else {
  5279. std::cerr << "comp_size=" << comp_size << " but required is " << (i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]) << std::endl;
  5280. }
  5281. } else {
  5282. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  5283. GGML_ASSERT(false);
  5284. }
  5285. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  5286. 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;
  5287. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->backend: " << tensor->backend << " 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;
  5288. if (src0 != nullptr) {
  5289. std::cerr << "src0=" << src0 << " src0->name=" << src0->name << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " backend=" << src0->backend << " 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;
  5290. }
  5291. if (src1 != nullptr) {
  5292. std::cerr << "src1=" << src1 << " src1->name=" << src1->name << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " backend=" << src1->backend << " 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;
  5293. }
  5294. 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;
  5295. std::cerr << std::endl << "Result:" << std::endl;
  5296. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  5297. std::cerr << std::endl << "Correct:" << std::endl;
  5298. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  5299. std::cerr << std::endl;
  5300. std::vector<const ggml_tensor *> done;
  5301. ggml_vk_print_graph_origin(tensor, done);
  5302. GGML_ASSERT(false);
  5303. }
  5304. if (first_error[0] == -1 && std::fabs(correct - result) > 0.1f) {
  5305. first_error[0] = i0;
  5306. first_error[1] = i1;
  5307. first_error[2] = i2;
  5308. first_error[3] = i3;
  5309. first_error_result = result;
  5310. first_error_correct = correct;
  5311. }
  5312. // Special case, value is infinite, avoid NaN result in avg_err
  5313. // NaN also appears in results, if both are nan error is 0
  5314. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  5315. avg_err += std::fabs(correct - result);
  5316. }
  5317. counter++;
  5318. }
  5319. }
  5320. }
  5321. }
  5322. avg_err /= counter;
  5323. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  5324. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  5325. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->backend: " << tensor->backend << " 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;
  5326. if (src0 != nullptr) {
  5327. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " backend=" << src0->backend << " 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;
  5328. }
  5329. if (src1 != nullptr) {
  5330. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " backend=" << src1->backend << " 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;
  5331. }
  5332. 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;
  5333. std::cerr << std::endl << "Result:" << std::endl;
  5334. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  5335. std::cerr << std::endl << "Correct:" << std::endl;
  5336. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  5337. std::cerr << std::endl;
  5338. std::cerr << std::endl << "Result:" << std::endl;
  5339. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 1, 0);
  5340. std::cerr << std::endl << "Correct:" << std::endl;
  5341. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 1, 0);
  5342. std::cerr << std::endl;
  5343. std::vector<const ggml_tensor *> done;
  5344. ggml_vk_print_graph_origin(tensor, done);
  5345. }
  5346. if (avg_err > 0.05 || std::isnan(avg_err)) {
  5347. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  5348. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->backend: " << tensor->backend << " 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;
  5349. if (src0 != nullptr) {
  5350. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " backend=" << src0->backend << " 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;
  5351. }
  5352. if (src1 != nullptr) {
  5353. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " backend=" << src1->backend << " 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;
  5354. }
  5355. 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;
  5356. std::cerr << std::endl << "Result:" << std::endl;
  5357. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  5358. std::cerr << std::endl << "Correct:" << std::endl;
  5359. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  5360. std::cerr << std::endl;
  5361. std::vector<const ggml_tensor *> done;
  5362. ggml_vk_print_graph_origin(tensor, done);
  5363. GGML_ASSERT(false);
  5364. } else {
  5365. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " backend=" << tensor->backend << " avg_err=" << avg_err << std::endl;
  5366. }
  5367. free(comp_result);
  5368. comp_result = nullptr;
  5369. comp_size = 0;
  5370. if (tensor->backend == GGML_BACKEND_TYPE_GPU) {
  5371. free(tensor_data);
  5372. }
  5373. }
  5374. void ggml_vk_check_results_1_cpu_assist(struct ggml_compute_params * params, struct ggml_tensor * tensor) {
  5375. ggml_backend_vk_context * ctx = &vk_instance.contexts[0];
  5376. ggml_vk_check_results_0(ctx, params, tensor);
  5377. }
  5378. #endif