ggml-vulkan.cpp 253 KB

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