ggml-vulkan.cpp 295 KB

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