ggml-vulkan.cpp 401 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_PERF) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. #include <vulkan/vulkan.hpp>
  8. #include <algorithm>
  9. #include <cmath>
  10. #include <iomanip>
  11. #include <iostream>
  12. #include <tuple>
  13. #include <vector>
  14. #include <sstream>
  15. #include <utility>
  16. #include <memory>
  17. #include <limits>
  18. #include <map>
  19. #include <unordered_map>
  20. #include <memory>
  21. #include <mutex>
  22. #include <future>
  23. #include <thread>
  24. #include "ggml-impl.h"
  25. #include "ggml-backend-impl.h"
  26. #include "ggml-vulkan-shaders.hpp"
  27. #define VK_API_VERSION VK_API_VERSION_1_2
  28. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  29. #define VK_VENDOR_ID_AMD 0x1002
  30. #define VK_VENDOR_ID_APPLE 0x106b
  31. #define VK_VENDOR_ID_INTEL 0x8086
  32. #define VK_VENDOR_ID_NVIDIA 0x10de
  33. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 32
  34. #define GGML_VK_MAX_NODES 8192
  35. #define MAX_VK_BUFFERS 256
  36. #ifndef K_QUANTS_PER_ITERATION
  37. #define K_QUANTS_PER_ITERATION 1
  38. #else
  39. static_assert(K_QUANTS_PER_ITERATION == 1 || K_QUANTS_PER_ITERATION == 2, "K_QUANTS_PER_ITERATION must be 1 or 2");
  40. #endif
  41. #define VK_CHECK(err, msg) \
  42. do { \
  43. vk::Result err_ = (err); \
  44. if (err_ != vk::Result::eSuccess) { \
  45. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  46. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  47. exit(1); \
  48. } \
  49. } while (0)
  50. #ifdef GGML_VULKAN_DEBUG
  51. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  52. #else
  53. #define VK_LOG_DEBUG(msg) ((void) 0)
  54. #endif // GGML_VULKAN_DEBUG
  55. struct ggml_backend_vk_context;
  56. struct vk_queue {
  57. uint32_t queue_family_index;
  58. vk::Queue queue;
  59. vk::CommandPool pool;
  60. uint32_t cmd_buffer_idx;
  61. std::vector<vk::CommandBuffer> cmd_buffers;
  62. vk::PipelineStageFlags stage_flags;
  63. bool transfer_only;
  64. };
  65. struct vk_pipeline_struct {
  66. std::string name;
  67. vk::ShaderModule shader_module;
  68. vk::DescriptorSetLayout dsl;
  69. std::vector<vk::DescriptorPool> descriptor_pools;
  70. std::vector<vk::DescriptorSet> descriptor_sets;
  71. uint32_t descriptor_set_idx;
  72. vk::PipelineLayout layout;
  73. vk::Pipeline pipeline;
  74. uint32_t push_constant_size;
  75. uint32_t parameter_count;
  76. std::array<uint32_t, 3> wg_denoms;
  77. uint32_t align;
  78. };
  79. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  80. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  81. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  82. struct vk_matmul_pipeline_struct {
  83. vk_pipeline l, m, s;
  84. vk_pipeline a_l, a_m, a_s;
  85. };
  86. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  87. struct vk_matmul_pipeline2 {
  88. vk_matmul_pipeline2() {
  89. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  90. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  91. }
  92. vk_matmul_pipeline f32acc;
  93. vk_matmul_pipeline f16acc;
  94. };
  95. struct vk_device_struct;
  96. typedef std::shared_ptr<vk_device_struct> vk_device;
  97. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  98. struct vk_buffer_struct;
  99. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  100. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  101. struct ggml_backend_vk_buffer_type_context {
  102. std::string name;
  103. vk_device device;
  104. };
  105. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  106. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  107. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  108. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  109. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  110. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  111. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  112. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  113. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  114. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  115. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  116. /* .is_host = */ NULL,
  117. };
  118. #ifdef GGML_VULKAN_MEMORY_DEBUG
  119. class vk_memory_logger;
  120. #endif
  121. #ifdef GGML_VULKAN_PERF
  122. class vk_perf_logger;
  123. #endif
  124. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  125. struct vk_device_struct {
  126. std::mutex mutex;
  127. vk::PhysicalDevice physical_device;
  128. vk::PhysicalDeviceProperties properties;
  129. std::string name;
  130. uint64_t max_memory_allocation_size;
  131. bool fp16;
  132. bool pipeline_robustness;
  133. vk::Device device;
  134. uint32_t vendor_id;
  135. vk_queue compute_queue;
  136. vk_queue transfer_queue;
  137. bool single_queue;
  138. uint32_t subgroup_size;
  139. uint32_t shader_core_count;
  140. bool uma;
  141. bool coopmat2;
  142. bool coopmat_support;
  143. bool coopmat_acc_f32_support;
  144. bool coopmat_acc_f16_support;
  145. uint32_t coopmat_m;
  146. uint32_t coopmat_n;
  147. uint32_t coopmat_k;
  148. size_t idx;
  149. bool mul_mat_l;
  150. bool mul_mat_m;
  151. bool mul_mat_s;
  152. bool mul_mat_id_l;
  153. bool mul_mat_id_m;
  154. bool mul_mat_id_s;
  155. vk_matmul_pipeline pipeline_matmul_f32;
  156. vk_matmul_pipeline pipeline_matmul_f32_f16;
  157. vk_matmul_pipeline2 pipeline_matmul_f16;
  158. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  159. vk_pipeline pipeline_matmul_split_k_reduce;
  160. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  161. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  162. vk_matmul_pipeline pipeline_matmul_id_f32;
  163. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  164. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  165. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  166. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  167. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_COUNT];
  168. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_COUNT];
  169. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  170. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32;
  171. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  172. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  173. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  174. vk_pipeline pipeline_acc_f32;
  175. vk_pipeline pipeline_add_f32, pipeline_add_f32_norepeat;
  176. vk_pipeline pipeline_add_f16_f32_f16, pipeline_add_f16_f32_f16_norepeat;
  177. vk_pipeline pipeline_mul_f32, pipeline_mul_f32_norepeat;
  178. vk_pipeline pipeline_div_f32, pipeline_div_f32_norepeat;
  179. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  180. vk_pipeline pipeline_upscale_f32;
  181. vk_pipeline pipeline_scale_f32;
  182. vk_pipeline pipeline_sqr_f32;
  183. vk_pipeline pipeline_sin_f32;
  184. vk_pipeline pipeline_cos_f32;
  185. vk_pipeline pipeline_clamp_f32;
  186. vk_pipeline pipeline_pad_f32;
  187. vk_pipeline pipeline_repeat_f32;
  188. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16;
  189. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16;
  190. vk_pipeline pipeline_norm_f32;
  191. vk_pipeline pipeline_group_norm_f32;
  192. vk_pipeline pipeline_rms_norm_f32;
  193. vk_pipeline pipeline_gelu_f32;
  194. vk_pipeline pipeline_gelu_quick_f32;
  195. vk_pipeline pipeline_silu_f32;
  196. vk_pipeline pipeline_relu_f32;
  197. vk_pipeline pipeline_leaky_relu_f32;
  198. vk_pipeline pipeline_tanh_f32;
  199. vk_pipeline pipeline_diag_mask_inf_f32;
  200. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  201. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  202. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16;
  203. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  204. vk_pipeline pipeline_argsort_f32;
  205. vk_pipeline pipeline_sum_rows_f32;
  206. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  207. vk_pipeline pipeline_timestep_embedding_f32;
  208. vk_pipeline pipeline_pool2d_f32;
  209. // [2][2][2] is for {f16acc,f32acc}x{large,small_rows}x{unaligned, aligned}
  210. vk_pipeline pipeline_flash_attn_f32_f16_D64[GGML_TYPE_COUNT][2][2][2];
  211. vk_pipeline pipeline_flash_attn_f32_f16_D80[GGML_TYPE_COUNT][2][2][2];
  212. vk_pipeline pipeline_flash_attn_f32_f16_D96[GGML_TYPE_COUNT][2][2][2];
  213. vk_pipeline pipeline_flash_attn_f32_f16_D112[GGML_TYPE_COUNT][2][2][2];
  214. vk_pipeline pipeline_flash_attn_f32_f16_D128[GGML_TYPE_COUNT][2][2][2];
  215. vk_pipeline pipeline_flash_attn_f32_f16_D256[GGML_TYPE_COUNT][2][2][2];
  216. std::unordered_map<std::string, vk_pipeline_ref> pipelines;
  217. std::unordered_map<std::string, uint64_t> pipeline_descriptor_set_requirements;
  218. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  219. vk::Fence fence;
  220. vk_buffer sync_staging;
  221. ggml_backend_buffer_type buffer_type;
  222. #ifdef GGML_VULKAN_MEMORY_DEBUG
  223. std::unique_ptr<vk_memory_logger> memory_logger;
  224. #endif
  225. #ifdef GGML_VULKAN_PERF
  226. std::unique_ptr<vk_perf_logger> perf_logger;
  227. #endif
  228. ~vk_device_struct() {
  229. VK_LOG_DEBUG("destroy device " << name);
  230. device.destroyFence(fence);
  231. ggml_vk_destroy_buffer(sync_staging);
  232. device.destroyCommandPool(compute_queue.pool);
  233. if (!single_queue) {
  234. device.destroyCommandPool(transfer_queue.pool);
  235. }
  236. for (auto& pipeline : pipelines) {
  237. if (pipeline.second.expired()) {
  238. continue;
  239. }
  240. vk_pipeline pl = pipeline.second.lock();
  241. ggml_vk_destroy_pipeline(device, pl);
  242. }
  243. pipelines.clear();
  244. device.destroy();
  245. }
  246. };
  247. struct vk_buffer_struct {
  248. vk::Buffer buffer = VK_NULL_HANDLE;
  249. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  250. vk::MemoryPropertyFlags memory_property_flags;
  251. void * ptr;
  252. size_t size = 0;
  253. vk_device device;
  254. ~vk_buffer_struct() {
  255. if (size == 0) {
  256. return;
  257. }
  258. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  259. device->device.freeMemory(device_memory);
  260. device->device.destroyBuffer(buffer);
  261. }
  262. };
  263. struct vk_subbuffer {
  264. vk_buffer buffer;
  265. uint64_t offset;
  266. uint64_t size;
  267. operator vk::DescriptorBufferInfo() const {
  268. return { buffer->buffer, offset, size };
  269. }
  270. };
  271. struct vk_semaphore {
  272. vk::Semaphore s;
  273. uint64_t value;
  274. };
  275. struct vk_submission {
  276. vk::CommandBuffer buffer;
  277. std::vector<vk_semaphore> wait_semaphores;
  278. std::vector<vk_semaphore> signal_semaphores;
  279. };
  280. typedef std::vector<vk_submission> vk_sequence;
  281. struct vk_mat_mat_push_constants {
  282. uint32_t M; uint32_t N; uint32_t K;
  283. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  284. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  285. uint32_t k_split;
  286. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  287. };
  288. struct vk_mat_vec_push_constants {
  289. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  290. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  291. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  292. };
  293. struct vk_mat_mat_id_push_constants {
  294. uint32_t M; uint32_t N; uint32_t K;
  295. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  296. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  297. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  298. };
  299. struct vk_mat_vec_id_push_constants {
  300. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  301. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  302. uint32_t nei0; uint32_t ne11;
  303. };
  304. struct vk_flash_attn_push_constants {
  305. uint32_t N;
  306. uint32_t KV;
  307. uint32_t ne1;
  308. uint32_t ne2;
  309. uint32_t ne3;
  310. uint32_t neq2;
  311. uint32_t neq3;
  312. uint32_t nek2;
  313. uint32_t nek3;
  314. uint32_t nev2;
  315. uint32_t nev3;
  316. uint32_t nem1;
  317. uint32_t nb02;
  318. uint32_t nb03;
  319. uint32_t nb12;
  320. uint32_t nb13;
  321. uint32_t nb22;
  322. uint32_t nb23;
  323. uint32_t nb31;
  324. float scale;
  325. float max_bias;
  326. float logit_softcap;
  327. uint32_t mask;
  328. uint32_t n_head_log2;
  329. float m0;
  330. float m1;
  331. };
  332. struct vk_op_push_constants {
  333. uint32_t KX;
  334. uint32_t KY;
  335. float param1;
  336. float param2;
  337. };
  338. struct vk_op_unary_push_constants {
  339. uint32_t ne;
  340. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  341. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  342. uint32_t d_offset;
  343. float param1; float param2;
  344. uint32_t ne0_012mp; uint32_t ne0_012L;
  345. uint32_t ne0_01mp; uint32_t ne0_01L;
  346. uint32_t ne0_0mp; uint32_t ne0_0L;
  347. uint32_t ne1_012mp; uint32_t ne1_012L;
  348. uint32_t ne1_01mp; uint32_t ne1_01L;
  349. uint32_t ne1_0mp; uint32_t ne1_0L;
  350. };
  351. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  352. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  353. // Precompute mp (m' in the paper) and L such that division
  354. // can be computed using a multiply (high 32b of 64b result)
  355. // and a shift:
  356. //
  357. // n/d = (mulhi(n, mp) + n) >> L;
  358. void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  359. {
  360. // compute L = ceil(log2(d));
  361. L = 0;
  362. while (L < 32 && (uint32_t{1} << L) < d) {
  363. L++;
  364. }
  365. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  366. }
  367. template <typename T> void init_pushconst_fastdiv(T &p) {
  368. static_assert(!std::is_const<T>::value, "unexpected type");
  369. }
  370. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  371. // Compute magic values to divide by these six numbers.
  372. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  373. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  374. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  375. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  376. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  377. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  378. }
  379. struct vk_op_binary_push_constants {
  380. uint32_t ne;
  381. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  382. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  383. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  384. uint32_t d_offset;
  385. float param1; float param2; int32_t param3;
  386. };
  387. struct vk_op_diag_mask_push_constants {
  388. uint32_t ncols;
  389. uint32_t rows_per_channel;
  390. int32_t n_past;
  391. };
  392. struct vk_op_rope_push_constants {
  393. uint32_t ncols;
  394. uint32_t n_dims;
  395. float freq_scale;
  396. uint32_t p_delta_rows;
  397. float freq_base;
  398. float ext_factor;
  399. float attn_factor;
  400. float corr_dims[2];
  401. float theta_scale;
  402. uint32_t has_ff;
  403. };
  404. struct vk_op_soft_max_push_constants {
  405. uint32_t KX;
  406. uint32_t KY;
  407. float scale;
  408. float max_bias;
  409. float m0;
  410. float m1;
  411. uint32_t n_head_log2;
  412. uint32_t nrows_x;
  413. };
  414. struct vk_op_argsort_push_constants {
  415. uint32_t ncols;
  416. uint32_t ncols_pad;
  417. int32_t order;
  418. };
  419. struct vk_op_im2col_push_constants {
  420. uint32_t batch_offset; uint32_t offset_delta;
  421. uint32_t IC;
  422. uint32_t IW; uint32_t IH;
  423. uint32_t OW; uint32_t OH;
  424. uint32_t KW; uint32_t KH;
  425. uint32_t pelements;
  426. uint32_t CHW;
  427. int32_t s0; int32_t s1;
  428. int32_t p0; int32_t p1;
  429. int32_t d0; int32_t d1;
  430. };
  431. struct vk_op_timestep_embedding_push_constants {
  432. uint32_t nb1;
  433. uint32_t dim;
  434. uint32_t max_period;
  435. };
  436. struct vk_op_pool2d_push_constants {
  437. uint32_t IW; uint32_t IH;
  438. uint32_t OW; uint32_t OH;
  439. uint32_t OC;
  440. uint32_t pelements;
  441. uint32_t op;
  442. int32_t k0; int32_t k1;
  443. int32_t s0; int32_t s1;
  444. int32_t p0; int32_t p1;
  445. };
  446. // Allow pre-recording command buffers
  447. struct vk_staging_memcpy {
  448. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  449. void * dst;
  450. const void * src;
  451. size_t n;
  452. };
  453. struct vk_op_upscale_push_constants {
  454. uint32_t ne; uint32_t d_offset;
  455. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  456. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  457. float sf0; float sf1; float sf2; float sf3;
  458. };
  459. struct vk_context_struct {
  460. vk_submission * s;
  461. std::vector<vk_sequence> seqs;
  462. int exit_tensor_idx;
  463. std::vector<vk_staging_memcpy> in_memcpys;
  464. std::vector<vk_staging_memcpy> out_memcpys;
  465. vk_queue * q;
  466. };
  467. typedef std::shared_ptr<vk_context_struct> vk_context;
  468. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  469. struct ggml_vk_garbage_collector {
  470. std::vector<vk_semaphore> tl_semaphores;
  471. std::vector<vk_semaphore> semaphores;
  472. std::vector<vk::Event> events;
  473. std::vector<vk_buffer> temp_buffers;
  474. std::vector<vk_context> contexts;
  475. };
  476. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  477. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  478. static std::string format_size(size_t size) {
  479. const size_t kib = 1024;
  480. const size_t mib = kib * 1024;
  481. const size_t gib = mib * 1024;
  482. std::ostringstream oss;
  483. oss << std::fixed << std::setprecision(2);
  484. if (size >= gib) {
  485. oss << static_cast<double>(size) / gib << " GiB";
  486. } else if (size >= mib) {
  487. oss << static_cast<double>(size) / mib << " MiB";
  488. } else if (size >= kib) {
  489. oss << static_cast<double>(size) / kib << " KiB";
  490. } else {
  491. oss << size << " B";
  492. }
  493. return oss.str();
  494. }
  495. static std::mutex log_mutex;
  496. class vk_memory_logger {
  497. public:
  498. vk_memory_logger(): total_device(0), total_host(0) {}
  499. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  500. void log_deallocation(vk_buffer_ref buf_ref);
  501. private:
  502. std::map<vk::Buffer, size_t> allocations; // Track allocations
  503. size_t total_device;
  504. size_t total_host;
  505. };
  506. #else
  507. #define VK_LOG_MEMORY(msg) ((void) 0)
  508. #endif // GGML_VULKAN_MEMORY_DEBUG
  509. #if defined(GGML_VULKAN_PERF)
  510. class vk_perf_logger {
  511. public:
  512. void print_timings() {
  513. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  514. for (const auto& t : timings) {
  515. uint64_t total = 0;
  516. for (const auto& time : t.second) {
  517. total += time;
  518. }
  519. std::cerr << t.first << ": " << t.second.size() << " x " << (total / t.second.size() / 1000.0) << " ms" << std::endl;
  520. }
  521. timings.clear();
  522. }
  523. void log_timing(const ggml_tensor * node, uint64_t time) {
  524. if (node->op == GGML_OP_UNARY) {
  525. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  526. return;
  527. }
  528. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  529. const uint64_t m = node->src[0]->ne[1];
  530. const uint64_t n = node->src[1]->ne[1];
  531. const uint64_t k = node->src[1]->ne[0];
  532. std::string name = ggml_op_name(node->op);
  533. if (n == 1) {
  534. name += "_VEC m=" + std::to_string(m) + " k=" + std::to_string(k);
  535. } else {
  536. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  537. }
  538. timings[name].push_back(time);
  539. return;
  540. }
  541. timings[ggml_op_name(node->op)].push_back(time);
  542. }
  543. private:
  544. std::map<std::string, std::vector<uint64_t>> timings;
  545. };
  546. #endif // GGML_VULKAN_PERF
  547. struct ggml_backend_vk_context {
  548. std::string name;
  549. vk_device device;
  550. size_t semaphore_idx, event_idx;
  551. ggml_vk_garbage_collector gc;
  552. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k;
  553. vk_buffer prealloc_x, prealloc_y, prealloc_split_k;
  554. vk::Fence fence;
  555. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  556. vk_context_ref compute_ctx;
  557. vk_context_ref transfer_ctx;
  558. std::vector<vk_context_ref> tensor_ctxs;
  559. };
  560. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  561. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  562. if (tensor->view_src) {
  563. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  564. }
  565. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  566. }
  567. struct ggml_backend_vk_buffer_context {
  568. vk_device_ref device;
  569. vk_buffer dev_buffer;
  570. std::string name;
  571. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  572. device(device),
  573. dev_buffer(dev_buffer),
  574. name(name) {
  575. }
  576. ~ggml_backend_vk_buffer_context() {
  577. ggml_vk_destroy_buffer(dev_buffer);
  578. }
  579. };
  580. #ifdef GGML_VULKAN_MEMORY_DEBUG
  581. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  582. std::lock_guard<std::mutex> guard(log_mutex);
  583. vk_buffer buf = buf_ref.lock();
  584. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  585. const std::string type = device ? "device" : "host";
  586. allocations[buf->buffer] = size;
  587. total_device += device ? size : 0;
  588. total_host += device ? 0 : size;
  589. VK_LOG_MEMORY(buf->device->name << ": +" << format_size(size) << " " << type << " at " << buf->buffer << ". Total device: " << format_size(total_device) << ", total host: " << format_size(total_host));
  590. }
  591. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  592. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  593. return;
  594. }
  595. std::lock_guard<std::mutex> guard(log_mutex);
  596. vk_buffer buf = buf_ref.lock();
  597. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  598. std::string type = device ? "device" : "host";
  599. auto it = allocations.find(buf->buffer);
  600. total_device -= device ? it->second : 0;
  601. total_host -= device ? 0 : it->second;
  602. if (it != allocations.end()) {
  603. VK_LOG_MEMORY(buf->device->name << ": -" << format_size(it->second) << " " << type << " at " << buf->buffer << ". Total device: " << format_size(total_device) << ", total host: " << format_size(total_host));
  604. allocations.erase(it);
  605. } else {
  606. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  607. }
  608. }
  609. #endif // GGML_VULKAN_MEMORY_DEBUG
  610. struct vk_instance_t {
  611. vk::Instance instance;
  612. std::vector<size_t> device_indices;
  613. vk_device devices[GGML_VK_MAX_DEVICES];
  614. };
  615. static bool vk_instance_initialized = false;
  616. static vk_instance_t vk_instance;
  617. #ifdef GGML_VULKAN_CHECK_RESULTS
  618. static size_t vk_skip_checks;
  619. static size_t vk_output_tensor;
  620. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  621. static void ggml_vk_check_results_0(ggml_tensor * tensor);
  622. static void ggml_vk_check_results_1(ggml_tensor * tensor);
  623. #endif
  624. 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);
  625. static void ggml_backend_vk_free(ggml_backend_t backend);
  626. // variables to track number of compiles in progress
  627. static uint32_t compile_count = 0;
  628. static std::mutex compile_count_mutex;
  629. static std::condition_variable compile_count_cond;
  630. static void ggml_vk_create_pipeline_func(vk_device& device, 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, bool disable_robustness) {
  631. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << name << ", " << entrypoint << ", " << parameter_count << ", " << push_constant_size << ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " << align << ")");
  632. GGML_ASSERT(parameter_count > 0);
  633. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  634. pipeline = std::make_shared<vk_pipeline_struct>();
  635. pipeline->name = name;
  636. pipeline->parameter_count = parameter_count;
  637. pipeline->push_constant_size = push_constant_size;
  638. pipeline->wg_denoms = wg_denoms;
  639. pipeline->align = align;
  640. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  641. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  642. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  643. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  644. for (uint32_t i = 0; i < parameter_count; i++) {
  645. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  646. dsl_binding_flags.push_back({});
  647. }
  648. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  649. vk::PushConstantRange pcr(
  650. vk::ShaderStageFlagBits::eCompute,
  651. 0,
  652. pipeline->push_constant_size
  653. );
  654. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  655. {},
  656. dsl_binding);
  657. descriptor_set_layout_create_info.setPNext(&dslbfci);
  658. pipeline->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  659. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  660. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  661. pipeline->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  662. pipeline->descriptor_set_idx = 0;
  663. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), pipeline->dsl, pcr);
  664. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  665. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  666. for (size_t i = 0; i < specialization_constants.size(); i++) {
  667. specialization_entries[i].constantID = i;
  668. specialization_entries[i].offset = i * sizeof(uint32_t);
  669. specialization_entries[i].size = sizeof(uint32_t);
  670. }
  671. vk::SpecializationInfo specialization_info(
  672. specialization_entries.size(),
  673. specialization_entries.data(),
  674. specialization_constants.size() * sizeof(uint32_t),
  675. specialization_constants.data()
  676. );
  677. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  678. vk::PipelineShaderStageCreateFlags(),
  679. vk::ShaderStageFlagBits::eCompute,
  680. pipeline->shader_module,
  681. entrypoint.c_str(),
  682. &specialization_info);
  683. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  684. vk::PipelineCreateFlags(),
  685. pipeline_shader_create_info,
  686. pipeline->layout);
  687. vk::PipelineRobustnessCreateInfoEXT rci;
  688. if (device->pipeline_robustness && disable_robustness) {
  689. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  690. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  691. compute_pipeline_create_info.setPNext(&rci);
  692. }
  693. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  694. {
  695. std::lock_guard<std::mutex> guard(device->mutex);
  696. device->pipelines.insert({ pipeline->name, pipeline });
  697. }
  698. {
  699. std::lock_guard<std::mutex> guard(compile_count_mutex);
  700. assert(compile_count > 0);
  701. compile_count--;
  702. // "Progress bar" for shader compiles
  703. static uint32_t total_compile_count = 0;
  704. if ((total_compile_count++ % 10) == 0) {
  705. std::cerr << ".";
  706. }
  707. }
  708. compile_count_cond.notify_all();
  709. }
  710. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  711. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  712. for (auto& pool : pipeline->descriptor_pools) {
  713. device.destroyDescriptorPool(pool);
  714. }
  715. pipeline->descriptor_pools.clear();
  716. pipeline->descriptor_sets.clear();
  717. pipeline->descriptor_set_idx = 0;
  718. device.destroyDescriptorSetLayout(pipeline->dsl);
  719. device.destroyPipelineLayout(pipeline->layout);
  720. device.destroyShaderModule(pipeline->shader_module);
  721. device.destroyPipeline(pipeline->pipeline);
  722. }
  723. static void ggml_pipeline_request_descriptor_sets(vk_device& device, vk_pipeline& pipeline, uint32_t n) {
  724. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  725. device->pipeline_descriptor_set_requirements[pipeline->name] += n;
  726. }
  727. static void ggml_pipeline_allocate_descriptor_sets(vk_device& device) {
  728. std::lock_guard<std::mutex> guard(device->mutex);
  729. for (auto& pair : device->pipeline_descriptor_set_requirements) {
  730. vk_pipeline pipeline = device->pipelines.at(pair.first).lock();
  731. const uint64_t n = pair.second;
  732. VK_LOG_DEBUG("ggml_pipeline_allocate_descriptor_sets(" << pipeline->name << ", " << n << ")");
  733. if (pipeline->descriptor_sets.size() >= pipeline->descriptor_set_idx + n) {
  734. // Enough descriptors are available
  735. continue;
  736. }
  737. uint32_t to_alloc = pipeline->descriptor_set_idx + n - pipeline->descriptor_sets.size();
  738. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - pipeline->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  739. uint32_t pool_idx = pipeline->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  740. while (to_alloc > 0) {
  741. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  742. to_alloc -= alloc_count;
  743. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  744. if (pool_idx >= pipeline->descriptor_pools.size()) {
  745. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  746. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  747. pipeline->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  748. }
  749. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  750. for (uint32_t i = 0; i < alloc_count; i++) {
  751. layouts[i] = pipeline->dsl;
  752. }
  753. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pipeline->descriptor_pools[pool_idx], alloc_count, layouts.data());
  754. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  755. pipeline->descriptor_sets.insert(pipeline->descriptor_sets.end(), sets.begin(), sets.end());
  756. pool_idx++;
  757. }
  758. }
  759. }
  760. static void ggml_pipeline_cleanup(vk_pipeline& pipeline) {
  761. VK_LOG_DEBUG("ggml_pipeline_cleanup(" << pipeline->name << ")");
  762. pipeline->descriptor_set_idx = 0;
  763. }
  764. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_queue& q) {
  765. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  766. std::lock_guard<std::mutex> guard(device->mutex);
  767. if (q.cmd_buffers.size() > q.cmd_buffer_idx) {
  768. // Reuse command buffer
  769. return q.cmd_buffers[q.cmd_buffer_idx++];
  770. }
  771. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  772. q.pool,
  773. vk::CommandBufferLevel::ePrimary,
  774. 1);
  775. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  776. auto buf = cmd_buffers.front();
  777. q.cmd_buffers.push_back(buf);
  778. q.cmd_buffer_idx++;
  779. return buf;
  780. }
  781. static vk_submission ggml_vk_create_submission(vk_device& device, vk_queue& q, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  782. VK_LOG_DEBUG("ggml_vk_create_submission()");
  783. vk_submission s;
  784. s.buffer = ggml_vk_create_cmd_buffer(device, q);
  785. s.wait_semaphores = std::move(wait_semaphores);
  786. s.signal_semaphores = std::move(signal_semaphores);
  787. return s;
  788. }
  789. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  790. if (ctx->seqs.empty()) {
  791. if (fence) {
  792. ctx->q->queue.submit({}, fence);
  793. }
  794. return;
  795. }
  796. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  797. std::vector<std::vector<uint64_t>> tl_wait_vals;
  798. std::vector<std::vector<uint64_t>> tl_signal_vals;
  799. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  800. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  801. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  802. std::vector<vk::SubmitInfo> submit_infos;
  803. int idx = -1;
  804. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  805. size_t reserve = 0;
  806. for (const auto& sequence : ctx->seqs) {
  807. reserve += sequence.size();
  808. }
  809. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  810. tl_wait_semaphores.reserve(reserve);
  811. tl_wait_vals.reserve(reserve);
  812. tl_signal_semaphores.reserve(reserve);
  813. tl_signal_vals.reserve(reserve);
  814. tl_submit_infos.reserve(reserve);
  815. submit_infos.reserve(reserve);
  816. stage_flags.reserve(reserve);
  817. for (const auto& sequence : ctx->seqs) {
  818. for (const auto& submission : sequence) {
  819. stage_flags.push_back({});
  820. idx++;
  821. tl_wait_vals.push_back({});
  822. tl_wait_semaphores.push_back({});
  823. tl_signal_vals.push_back({});
  824. tl_signal_semaphores.push_back({});
  825. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  826. stage_flags[idx].push_back(ctx->q->stage_flags);
  827. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  828. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  829. }
  830. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  831. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  832. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  833. }
  834. tl_submit_infos.push_back({
  835. (uint32_t) submission.wait_semaphores.size(),
  836. tl_wait_vals[idx].data(),
  837. (uint32_t) submission.signal_semaphores.size(),
  838. tl_signal_vals[idx].data(),
  839. });
  840. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  841. tl_submit_infos[idx].pNext = nullptr;
  842. vk::SubmitInfo si{
  843. (uint32_t) submission.wait_semaphores.size(),
  844. tl_wait_semaphores[idx].data(),
  845. stage_flags[idx].data(),
  846. 1,
  847. &submission.buffer,
  848. (uint32_t) submission.signal_semaphores.size(),
  849. tl_signal_semaphores[idx].data(),
  850. };
  851. si.setPNext(&tl_submit_infos[idx]);
  852. submit_infos.push_back(si);
  853. }
  854. }
  855. ctx->q->queue.submit(submit_infos, fence);
  856. ctx->seqs.clear();
  857. }
  858. 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) {
  859. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  860. const uint32_t qfsize = queue_family_props.size();
  861. // Try with avoid preferences first
  862. for (uint32_t i = 0; i < qfsize; i++) {
  863. 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)) {
  864. return i;
  865. }
  866. }
  867. // Fall back to only required
  868. for (size_t i = 0; i < qfsize; i++) {
  869. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  870. return i;
  871. }
  872. }
  873. // Fall back to reusing compute queue
  874. for (size_t i = 0; i < qfsize; i++) {
  875. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  876. return i;
  877. }
  878. }
  879. // Fall back to ignoring min_num_queries
  880. for (size_t i = 0; i < qfsize; i++) {
  881. if (queue_family_props[i].queueFlags & required) {
  882. return i;
  883. }
  884. }
  885. // 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.
  886. // 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.
  887. if (compute_index >= 0) {
  888. return compute_index;
  889. }
  890. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  891. for(auto &q_family : queue_family_props) {
  892. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  893. }
  894. abort();
  895. }
  896. static void ggml_vk_create_queue(vk_device& device, vk_queue& q, uint32_t queue_family_index, uint32_t queue_index, vk::PipelineStageFlags&& stage_flags, bool transfer_only) {
  897. VK_LOG_DEBUG("ggml_vk_create_queue()");
  898. std::lock_guard<std::mutex> guard(device->mutex);
  899. q.queue_family_index = queue_family_index;
  900. q.transfer_only = transfer_only;
  901. vk::CommandPoolCreateInfo command_pool_create_info_compute(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), queue_family_index);
  902. q.pool = device->device.createCommandPool(command_pool_create_info_compute);
  903. q.cmd_buffer_idx = 0;
  904. q.queue = device->device.getQueue(queue_family_index, queue_index);
  905. q.stage_flags = stage_flags;
  906. }
  907. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_queue& q) {
  908. vk_context result = std::make_shared<vk_context_struct>();
  909. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  910. ctx->gc.contexts.emplace_back(result);
  911. result->q = &q;
  912. return result;
  913. }
  914. static vk_context ggml_vk_create_temporary_context(vk_queue& q) {
  915. vk_context result = std::make_shared<vk_context_struct>();
  916. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  917. result->q = &q;
  918. return result;
  919. }
  920. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  921. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  922. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  923. vk::SemaphoreCreateInfo ci{};
  924. ci.setPNext(&tci);
  925. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  926. ctx->gc.semaphores.push_back({ semaphore, 0 });
  927. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  928. }
  929. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  930. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  931. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  932. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  933. vk::SemaphoreCreateInfo ci{};
  934. ci.setPNext(&tci);
  935. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  936. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  937. }
  938. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  939. }
  940. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  941. if (ctx->event_idx >= ctx->gc.events.size()) {
  942. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  943. }
  944. return ctx->gc.events[ctx->event_idx++];
  945. }
  946. static void ggml_vk_queue_cleanup(vk_device& device, vk_queue& q) {
  947. VK_LOG_DEBUG("ggml_vk_queue_cleanup()");
  948. std::lock_guard<std::mutex> guard(device->mutex);
  949. // Requires command buffers to be done
  950. device->device.resetCommandPool(q.pool);
  951. q.cmd_buffer_idx = 0;
  952. }
  953. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  954. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  955. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  956. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  957. (flags & memory_type.propertyFlags) == flags &&
  958. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  959. return static_cast<int32_t>(i);
  960. }
  961. }
  962. return UINT32_MAX;
  963. }
  964. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  965. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags) << ", " << to_string(fallback_flags) << ")");
  966. if (size > device->max_memory_allocation_size) {
  967. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device memory allocation limit");
  968. }
  969. std::lock_guard<std::mutex> guard(device->mutex);
  970. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  971. if (size == 0) {
  972. buf->size = 0;
  973. return buf;
  974. }
  975. vk::BufferCreateInfo buffer_create_info{
  976. vk::BufferCreateFlags(),
  977. size,
  978. vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst,
  979. vk::SharingMode::eExclusive,
  980. 0,
  981. nullptr,
  982. };
  983. buf->buffer = device->device.createBuffer(buffer_create_info);
  984. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  985. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  986. uint32_t memory_type_index = UINT32_MAX;
  987. memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  988. buf->memory_property_flags = req_flags;
  989. if (memory_type_index == UINT32_MAX && fallback_flags) {
  990. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  991. buf->memory_property_flags = fallback_flags;
  992. }
  993. if (memory_type_index == UINT32_MAX) {
  994. device->device.destroyBuffer(buf->buffer);
  995. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  996. }
  997. try {
  998. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  999. } catch (const vk::SystemError& e) {
  1000. if (buf->memory_property_flags != fallback_flags) {
  1001. // Try again with fallback flags
  1002. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  1003. buf->memory_property_flags = fallback_flags;
  1004. try {
  1005. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1006. }
  1007. catch (const vk::SystemError& e) {
  1008. device->device.destroyBuffer(buf->buffer);
  1009. throw e;
  1010. }
  1011. } else {
  1012. // Out of Host/Device memory, clean up buffer
  1013. device->device.destroyBuffer(buf->buffer);
  1014. throw e;
  1015. }
  1016. }
  1017. buf->ptr = nullptr;
  1018. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1019. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1020. }
  1021. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1022. buf->device = device;
  1023. buf->size = size;
  1024. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1025. device->memory_logger->log_allocation(buf, size);
  1026. #endif
  1027. return buf;
  1028. }
  1029. static vk_buffer ggml_vk_create_buffer_check(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  1030. try {
  1031. return ggml_vk_create_buffer(device, size, req_flags, fallback_flags);
  1032. } catch (const vk::SystemError& e) {
  1033. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1034. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1035. throw e;
  1036. }
  1037. }
  1038. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1039. vk_buffer buf;
  1040. try {
  1041. if (device->uma) {
  1042. // Fall back to host memory type
  1043. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1044. } else {
  1045. // use rebar if available, otherwise fallback to device only visible memory
  1046. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1047. }
  1048. } catch (const vk::SystemError& e) {
  1049. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1050. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1051. throw e;
  1052. }
  1053. return buf;
  1054. }
  1055. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1056. if (buf == nullptr) {
  1057. return;
  1058. }
  1059. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1060. if (buf->device != nullptr) {
  1061. buf->device->memory_logger->log_deallocation(buf);
  1062. }
  1063. #endif
  1064. buf.reset();
  1065. }
  1066. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  1067. return { buf, 0, VK_WHOLE_SIZE };
  1068. }
  1069. static void ggml_vk_sync_buffers(vk_context& ctx) {
  1070. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1071. const bool transfer_queue = ctx->q->transfer_only;
  1072. ctx->s->buffer.pipelineBarrier(
  1073. ctx->q->stage_flags,
  1074. ctx->q->stage_flags,
  1075. {},
  1076. { {
  1077. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1078. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1079. } },
  1080. {},
  1081. {}
  1082. );
  1083. }
  1084. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1085. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1086. if (events.empty()) {
  1087. return;
  1088. }
  1089. ctx->s->buffer.waitEvents(
  1090. events,
  1091. ctx->q->stage_flags,
  1092. ctx->q->stage_flags,
  1093. {},
  1094. {},
  1095. {}
  1096. );
  1097. }
  1098. // number of rows/cols for flash attention shader
  1099. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1100. static std::array<uint32_t, 2> fa_rows_cols(uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) {
  1101. GGML_UNUSED(clamp);
  1102. // small rows, large cols
  1103. if (small_rows) {
  1104. return {flash_attention_num_small_rows, 128};
  1105. }
  1106. // small cols to reduce register count
  1107. if (ggml_is_quantized(type) || D == 256) {
  1108. return {64, 32};
  1109. }
  1110. return {64, 64};
  1111. };
  1112. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id) {
  1113. // Needs to be kept up to date on shader changes
  1114. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  1115. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  1116. const uint32_t warps = warptile[0] / device->subgroup_size;
  1117. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  1118. const uint32_t mmid_row_ids = mul_mat_id ? 3072 * sizeof(uint32_t) : 0;
  1119. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  1120. return (load_bufs + mmid_row_ids + coopmat_stage) <= device->properties.limits.maxComputeSharedMemorySize;
  1121. }
  1122. static void ggml_vk_load_shaders(vk_device& device) {
  1123. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  1124. std::cerr << "ggml_vulkan: Compiling shaders";
  1125. // some shaders require the subgroup size to be 16 or larger
  1126. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  1127. // mulmat
  1128. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  1129. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  1130. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  1131. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid;
  1132. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  1133. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  1134. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  1135. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  1136. uint32_t l_align, m_align, s_align;
  1137. if (device->coopmat2) {
  1138. // spec constants and tile sizes for non-quant matmul/matmul_id
  1139. l_warptile = { 256, 128, 256, 64 };
  1140. m_warptile = { 256, 128, 128, 64 };
  1141. s_warptile = { 128, 32, 16, 64 };
  1142. l_wg_denoms = {128, 256, 1 };
  1143. m_wg_denoms = {128, 128, 1 };
  1144. s_wg_denoms = { 32, 16, 1 };
  1145. // spec constants and tile sizes for quant matmul (non-Qi_K)
  1146. l_warptile_mmq = { 256, 128, 256, 64 };
  1147. m_warptile_mmq = { 256, 128, 128, 64 };
  1148. s_warptile_mmq = { 256, 128, 128, 64 };
  1149. l_mmq_wg_denoms = { 128, 256, 1 };
  1150. m_mmq_wg_denoms = { 128, 128, 1 };
  1151. s_mmq_wg_denoms = { 128, 128, 1 };
  1152. // spec constants and tile sizes for quant matmul (Qi_K)
  1153. l_warptile_mmq_k = { 256, 128, 512, 16 };
  1154. m_warptile_mmq_k = { 256, 128, 256, 16 };
  1155. s_warptile_mmq_k = { 256, 32, 128, 64 };
  1156. l_mmq_wg_denoms_k = { 128, 512, 1 };
  1157. m_mmq_wg_denoms_k = { 128, 256, 1 };
  1158. s_mmq_wg_denoms_k = { 32, 128, 1 };
  1159. // spec constants and tile sizes for quant matmul_id
  1160. l_warptile_mmqid = { 256, 128, 128, 16 };
  1161. m_warptile_mmqid = { 256, 128, 64, 16 };
  1162. s_warptile_mmqid = { 256, 64, 64, 16 };
  1163. l_mmqid_wg_denoms = { 128, 128, 1 };
  1164. m_mmqid_wg_denoms = { 128, 64, 1 };
  1165. s_mmqid_wg_denoms = { 64, 64, 1 };
  1166. l_align = 128;
  1167. m_align = 64;
  1168. s_align = 32;
  1169. } else {
  1170. // Matrix cores require different warp group sizes
  1171. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  1172. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  1173. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  1174. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  1175. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  1176. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  1177. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  1178. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  1179. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  1180. l_warptile = { 128, 128, 128, 16, device->subgroup_size * 2, 64, 2, tm_l, tn_l, tk_l, device->subgroup_size };
  1181. m_warptile = { 128, 64, 64, 16, device->subgroup_size, 32, 2, tm_m, tn_m, tk_m, device->subgroup_size };
  1182. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, device->subgroup_size };
  1183. l_warptile_mmq = { 128, 128, 128, 32, device->subgroup_size * 2, 64, 2, tm_l, tn_l, tk_l, device->subgroup_size };
  1184. m_warptile_mmq = { 128, 64, 64, 32, device->subgroup_size, 32, 2, tm_m, tn_m, tk_m, device->subgroup_size };
  1185. s_warptile_mmq = { subgroup_size_16, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, device->subgroup_size };
  1186. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  1187. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  1188. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  1189. l_align = 128;
  1190. m_align = 64;
  1191. s_align = 32;
  1192. // Fallback to smaller sizes if there's not enough shared memory. Given the current shaders
  1193. // and tile sizes, this should handle 16KB, 32KB, and 48KB+.
  1194. // This logic doesn't explicitly account for the 12KB row_ids in the mul_mat_mat_id shaders.
  1195. // But the numbers happen to work out for 32KB shared memory size that when using the medium
  1196. // size there's enough room for everything, and we assert for this.
  1197. uint32_t shmem_needed = (l_warptile[1] + l_warptile[2]) * (l_warptile[3] + 1) * sizeof(float);
  1198. if (shmem_needed > device->properties.limits.maxComputeSharedMemorySize) {
  1199. l_warptile = m_warptile;
  1200. l_wg_denoms = m_wg_denoms;
  1201. shmem_needed = (l_warptile[1] + l_warptile[2]) * (l_warptile[3] + 1) * sizeof(float);
  1202. GGML_ASSERT(shmem_needed <= device->properties.limits.maxComputeSharedMemorySize);
  1203. }
  1204. if (device->properties.limits.maxComputeSharedMemorySize >= 32768) {
  1205. // assert mul_mat_mat_id shaders will fit.
  1206. GGML_ASSERT(shmem_needed + 3072*4 <= device->properties.limits.maxComputeSharedMemorySize);
  1207. }
  1208. shmem_needed = (l_warptile_mmq[1] + l_warptile_mmq[2]) * (l_warptile_mmq[3] + 1) * sizeof(float);
  1209. if (shmem_needed > device->properties.limits.maxComputeSharedMemorySize) {
  1210. if (device->properties.limits.maxComputeSharedMemorySize == 32768) {
  1211. l_warptile_mmq = m_warptile_mmq;
  1212. l_mmq_wg_denoms = m_mmq_wg_denoms;
  1213. } else {
  1214. l_warptile_mmq = s_warptile_mmq;
  1215. l_mmq_wg_denoms = s_mmq_wg_denoms;
  1216. }
  1217. shmem_needed = (l_warptile_mmq[1] + l_warptile_mmq[2]) * (l_warptile_mmq[3] + 1) * sizeof(float);
  1218. GGML_ASSERT(shmem_needed <= device->properties.limits.maxComputeSharedMemorySize);
  1219. }
  1220. if (device->properties.limits.maxComputeSharedMemorySize >= 32768) {
  1221. // assert mul_mat_mat_id shaders will fit.
  1222. GGML_ASSERT(shmem_needed + 3072*4 <= device->properties.limits.maxComputeSharedMemorySize);
  1223. }
  1224. // Disable medium and large matrix multiplication if not enough shared memory is available
  1225. // Check mmq warptiles as the largest configuration
  1226. // Throw an error if not enough for any matrix multiplication is available
  1227. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false)) {
  1228. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  1229. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  1230. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false)) {
  1231. device->mul_mat_m = false;
  1232. device->mul_mat_l = false;
  1233. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false)) {
  1234. device->mul_mat_l = false;
  1235. }
  1236. // Disable mul_mat_id if not enough shared memory is available
  1237. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, true)) {
  1238. device->mul_mat_id_s = false;
  1239. device->mul_mat_id_m = false;
  1240. device->mul_mat_id_l = false;
  1241. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, true)) {
  1242. device->mul_mat_id_m = false;
  1243. device->mul_mat_id_l = false;
  1244. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, true)) {
  1245. device->mul_mat_id_l = false;
  1246. }
  1247. }
  1248. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1249. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  1250. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1251. std::vector<std::future<void>> compiles;
  1252. auto const &ggml_vk_create_pipeline = [&](vk_device& device, 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, const std::vector<uint32_t>& specialization_constants, uint32_t align, bool disable_robustness = false) {
  1253. {
  1254. // wait until fewer than N compiles are in progress
  1255. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  1256. std::unique_lock<std::mutex> guard(compile_count_mutex);
  1257. while (compile_count >= N) {
  1258. compile_count_cond.wait(guard);
  1259. }
  1260. compile_count++;
  1261. }
  1262. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), name, spv_size, spv_data, entrypoint, parameter_count, push_constant_size, wg_denoms, specialization_constants, align, disable_robustness));
  1263. };
  1264. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1265. if (device->coopmat2) {
  1266. auto const &fa_wg_denoms = [&](uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  1267. return {fa_rows_cols(D, clamp, type, small_rows)[0], 1, 1};
  1268. };
  1269. auto const &fa_spec_constants = [&](uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  1270. // For large number of rows, 128 invocations seems to work best.
  1271. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  1272. // can't use 256 for D==80.
  1273. uint32_t wg_size = (small_rows && (D % 32) == 0) ? 256 : 128;
  1274. auto rows_cols = fa_rows_cols(D, clamp, type, small_rows);
  1275. return {wg_size, rows_cols[0], rows_cols[1], (D), clamp};
  1276. };
  1277. #define CREATE_FA2(TYPE, NAMELC, D) \
  1278. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][0][0], "flash_attn_f32_f16_D" #D "_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,false), fa_spec_constants(D,1,TYPE,false), 1); \
  1279. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][0][1], "flash_attn_f32_f16_D" #D "_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,false), fa_spec_constants(D,0,TYPE,false), fa_rows_cols(D,0,TYPE,false)[1]); \
  1280. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][0][0], "flash_attn_f32_f16_D" #D "_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,false), fa_spec_constants(D,1,TYPE,false), 1); \
  1281. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][0][1], "flash_attn_f32_f16_D" #D "_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,false), fa_spec_constants(D,0,TYPE,false), fa_rows_cols(D,0,TYPE,false)[1]); \
  1282. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][1][0], "flash_attn_f32_f16_D" #D "_f16acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,true), fa_spec_constants(D,1,TYPE,true), 1); \
  1283. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][1][1], "flash_attn_f32_f16_D" #D "_aligned_f16acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,true), fa_spec_constants(D,0,TYPE,true), fa_rows_cols(D,0,TYPE,true)[1]); \
  1284. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][1][0], "flash_attn_f32_f16_D" #D "_f32acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,true), fa_spec_constants(D,1,TYPE,true), 1); \
  1285. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][1][1], "flash_attn_f32_f16_D" #D "_aligned_f32acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,true), fa_spec_constants(D,0,TYPE,true), fa_rows_cols(D,0,TYPE,true)[1]); \
  1286. #define CREATE_FA(TYPE, NAMELC) \
  1287. CREATE_FA2(TYPE, NAMELC, 64) \
  1288. CREATE_FA2(TYPE, NAMELC, 80) \
  1289. CREATE_FA2(TYPE, NAMELC, 96) \
  1290. CREATE_FA2(TYPE, NAMELC, 112) \
  1291. CREATE_FA2(TYPE, NAMELC, 128) \
  1292. CREATE_FA2(TYPE, NAMELC, 256)
  1293. CREATE_FA(GGML_TYPE_F16, f16)
  1294. CREATE_FA(GGML_TYPE_Q4_0, q4_0)
  1295. CREATE_FA(GGML_TYPE_Q4_1, q4_1)
  1296. CREATE_FA(GGML_TYPE_Q5_0, q5_0)
  1297. CREATE_FA(GGML_TYPE_Q5_1, q5_1)
  1298. CREATE_FA(GGML_TYPE_Q8_0, q8_0)
  1299. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  1300. //CREATE_FA(GGML_TYPE_Q2_K, q2_k)
  1301. //CREATE_FA(GGML_TYPE_Q3_K, q3_k)
  1302. //CREATE_FA(GGML_TYPE_Q4_K, q4_k)
  1303. //CREATE_FA(GGML_TYPE_Q5_K, q5_k)
  1304. //CREATE_FA(GGML_TYPE_Q6_K, q6_k)
  1305. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl)
  1306. #undef CREATE_FA
  1307. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1308. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1309. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  1310. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  1311. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  1312. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  1313. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  1314. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  1315. // Create 2 variants, {f16,f32} accumulator
  1316. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1317. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1318. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1319. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1320. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1321. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1322. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1323. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1324. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1325. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1326. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1327. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1328. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1329. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1330. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1331. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1332. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1333. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1334. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  1335. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  1336. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  1337. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1338. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1339. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1340. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1341. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1342. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1343. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1344. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1345. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1346. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1347. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1348. #undef CREATE_MM
  1349. #undef CREATE_MM2
  1350. } else
  1351. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1352. if (device->coopmat_support) {
  1353. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1354. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1355. if (device->mul_mat ## ID ## _l) \
  1356. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  1357. if (device->mul_mat ## ID ## _m) \
  1358. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  1359. if (device->mul_mat ## ID ## _s) \
  1360. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  1361. if (device->mul_mat ## ID ## _l) \
  1362. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  1363. if (device->mul_mat ## ID ## _m) \
  1364. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  1365. if (device->mul_mat ## ID ## _s) \
  1366. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  1367. // Create 2 variants, {f16,f32} accumulator
  1368. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1369. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1370. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1371. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1372. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1373. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1374. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1375. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1376. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1377. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1378. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1379. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1380. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1381. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1382. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1383. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1384. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1385. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1386. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1387. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1388. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1389. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1390. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1391. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1392. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1393. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1394. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1395. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1396. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1397. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1398. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1399. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1400. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1401. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, _f16acc, wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1402. }
  1403. #undef CREATE_MM
  1404. } else if (device->fp16) {
  1405. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1406. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1407. if (device->mul_mat ## ID ## _l) \
  1408. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  1409. if (device->mul_mat ## ID ## _m) \
  1410. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  1411. if (device->mul_mat ## ID ## _s) \
  1412. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  1413. if (device->mul_mat ## ID ## _l) \
  1414. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  1415. if (device->mul_mat ## ID ## _m) \
  1416. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  1417. if (device->mul_mat ## ID ## _s) \
  1418. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  1419. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1420. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1421. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1422. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1423. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1424. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1425. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1426. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1427. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1428. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1429. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1430. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1431. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1432. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1433. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1434. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1435. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1436. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1437. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1438. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1439. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1440. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1441. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1442. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1443. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1444. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1445. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1446. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1447. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1448. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1449. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1450. }
  1451. #undef CREATE_MM
  1452. } else {
  1453. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1454. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1455. if (device->mul_mat ## ID ## _l) \
  1456. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  1457. if (device->mul_mat ## ID ## _m) \
  1458. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  1459. if (device->mul_mat ## ID ## _s) \
  1460. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  1461. if (device->mul_mat ## ID ## _l) \
  1462. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  1463. if (device->mul_mat ## ID ## _m) \
  1464. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  1465. if (device->mul_mat ## ID ## _s) \
  1466. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  1467. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1468. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1469. CREATE_MM(pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1470. CREATE_MM(pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1471. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1472. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1473. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1474. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1475. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1476. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1477. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1478. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1479. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1480. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1481. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1482. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1483. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1484. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1485. CREATE_MM(pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1486. CREATE_MM(pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1487. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1488. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1489. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1490. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1491. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1492. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1493. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1494. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1495. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1496. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1497. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1498. }
  1499. #undef CREATE_MM2
  1500. #undef CREATE_MM
  1501. }
  1502. // mul mat vec
  1503. // computing two rows per workgroup is a benefit for Q4_0 -> Q5_1, but not for Q8_0.
  1504. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F32 ], "mul_mat_vec_f32_f32_f32", mul_mat_vec_f32_f32_f32_len, mul_mat_vec_f32_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1505. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F16 ], "mul_mat_vec_f16_f32_f32", mul_mat_vec_f16_f32_f32_len, mul_mat_vec_f16_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1506. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_0], "mul_mat_vec_q4_0_f32_f32", mul_mat_vec_q4_0_f32_f32_len, mul_mat_vec_q4_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1507. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_1], "mul_mat_vec_q4_1_f32_f32", mul_mat_vec_q4_1_f32_f32_len, mul_mat_vec_q4_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1508. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_0], "mul_mat_vec_q5_0_f32_f32", mul_mat_vec_q5_0_f32_f32_len, mul_mat_vec_q5_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1509. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_1], "mul_mat_vec_q5_1_f32_f32", mul_mat_vec_q5_1_f32_f32_len, mul_mat_vec_q5_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1510. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q8_0], "mul_mat_vec_q8_0_f32_f32", mul_mat_vec_q8_0_f32_f32_len, mul_mat_vec_q8_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size, 1}, 1, true);
  1511. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q2_K], "mul_mat_vec_q2_k_f32_f32", mul_mat_vec_q2_k_f32_f32_len, mul_mat_vec_q2_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1512. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q3_K], "mul_mat_vec_q3_k_f32_f32", mul_mat_vec_q3_k_f32_f32_len, mul_mat_vec_q3_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1513. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_K], "mul_mat_vec_q4_k_f32_f32", mul_mat_vec_q4_k_f32_f32_len, mul_mat_vec_q4_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1514. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_K], "mul_mat_vec_q5_k_f32_f32", mul_mat_vec_q5_k_f32_f32_len, mul_mat_vec_q5_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1515. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q6_K], "mul_mat_vec_q6_k_f32_f32", mul_mat_vec_q6_k_f32_f32_len, mul_mat_vec_q6_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {subgroup_size_16}, 1, true);
  1516. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_iq4_nl_f32_f32", mul_mat_vec_iq4_nl_f32_f32_len, mul_mat_vec_iq4_nl_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1517. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F32 ], "mul_mat_vec_f32_f16_f32", mul_mat_vec_f32_f16_f32_len, mul_mat_vec_f32_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1518. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F16 ], "mul_mat_vec_f16_f16_f32", mul_mat_vec_f16_f16_f32_len, mul_mat_vec_f16_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1519. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_0], "mul_mat_vec_q4_0_f16_f32", mul_mat_vec_q4_0_f16_f32_len, mul_mat_vec_q4_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1520. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_1], "mul_mat_vec_q4_1_f16_f32", mul_mat_vec_q4_1_f16_f32_len, mul_mat_vec_q4_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1521. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_0], "mul_mat_vec_q5_0_f16_f32", mul_mat_vec_q5_0_f16_f32_len, mul_mat_vec_q5_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1522. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_1], "mul_mat_vec_q5_1_f16_f32", mul_mat_vec_q5_1_f16_f32_len, mul_mat_vec_q5_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1523. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q8_0], "mul_mat_vec_q8_0_f16_f32", mul_mat_vec_q8_0_f16_f32_len, mul_mat_vec_q8_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size, 1}, 1, true);
  1524. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q2_K], "mul_mat_vec_q2_k_f16_f32", mul_mat_vec_q2_k_f16_f32_len, mul_mat_vec_q2_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1525. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q3_K], "mul_mat_vec_q3_k_f16_f32", mul_mat_vec_q3_k_f16_f32_len, mul_mat_vec_q3_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1526. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_K], "mul_mat_vec_q4_k_f16_f32", mul_mat_vec_q4_k_f16_f32_len, mul_mat_vec_q4_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1527. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_K], "mul_mat_vec_q5_k_f16_f32", mul_mat_vec_q5_k_f16_f32_len, mul_mat_vec_q5_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1528. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q6_K], "mul_mat_vec_q6_k_f16_f32", mul_mat_vec_q6_k_f16_f32_len, mul_mat_vec_q6_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {subgroup_size_16}, 1, true);
  1529. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_iq4_nl_f16_f32", mul_mat_vec_iq4_nl_f16_f32_len, mul_mat_vec_iq4_nl_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size}, 1, true);
  1530. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", mul_mat_vec_id_f32_f32_len, mul_mat_vec_id_f32_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1531. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", mul_mat_vec_id_f16_f32_len, mul_mat_vec_id_f16_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  1532. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", mul_mat_vec_id_q4_0_f32_len, mul_mat_vec_id_q4_0_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1533. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", mul_mat_vec_id_q4_1_f32_len, mul_mat_vec_id_q4_1_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1534. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", mul_mat_vec_id_q5_0_f32_len, mul_mat_vec_id_q5_0_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1535. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", mul_mat_vec_id_q5_1_f32_len, mul_mat_vec_id_q5_1_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1536. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", mul_mat_vec_id_q8_0_f32_len, mul_mat_vec_id_q8_0_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size, 1}, 1, true);
  1537. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", mul_mat_vec_id_q2_k_f32_len, mul_mat_vec_id_q2_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1538. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", mul_mat_vec_id_q3_k_f32_len, mul_mat_vec_id_q3_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1539. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", mul_mat_vec_id_q4_k_f32_len, mul_mat_vec_id_q4_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1540. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", mul_mat_vec_id_q5_k_f32_len, mul_mat_vec_id_q5_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {device->subgroup_size}, 1, true);
  1541. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", mul_mat_vec_id_q6_k_f32_len, mul_mat_vec_id_q6_k_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {subgroup_size_16}, 1, true);
  1542. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", mul_mat_vec_id_iq4_nl_f32_len, mul_mat_vec_id_iq4_nl_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1, true);
  1543. // dequant shaders
  1544. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_F32 ], "f32_to_f16", dequant_f32_len, dequant_f32_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1545. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_0], "dequant_q4_0", dequant_q4_0_len, dequant_q4_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1546. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_1], "dequant_q4_1", dequant_q4_1_len, dequant_q4_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1547. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_0], "dequant_q5_0", dequant_q5_0_len, dequant_q5_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1548. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_1], "dequant_q5_1", dequant_q5_1_len, dequant_q5_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1549. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q8_0], "dequant_q8_0", dequant_q8_0_len, dequant_q8_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1550. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q2_K], "dequant_q2_k", dequant_q2_k_len, dequant_q2_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  1551. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q3_K], "dequant_q3_k", dequant_q3_k_len, dequant_q3_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  1552. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_K], "dequant_q4_k", dequant_q4_k_len, dequant_q4_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  1553. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_K], "dequant_q5_k", dequant_q5_k_len, dequant_q5_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  1554. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q6_K], "dequant_q6_k", dequant_q6_k_len, dequant_q6_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  1555. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_NL], "dequant_iq4_nl", dequant_iq4_nl_len, dequant_iq4_nl_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  1556. // get_rows
  1557. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F32 ], "get_rows_f32", get_rows_f32_len, get_rows_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  1558. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F16 ], "get_rows_f16", get_rows_f16_len, get_rows_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  1559. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_0], "get_rows_q4_0", get_rows_q4_0_len, get_rows_q4_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1560. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_1], "get_rows_q4_1", get_rows_q4_1_len, get_rows_q4_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1561. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_0], "get_rows_q5_0", get_rows_q5_0_len, get_rows_q5_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1562. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_1], "get_rows_q5_1", get_rows_q5_1_len, get_rows_q5_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1563. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q8_0], "get_rows_q8_0", get_rows_q8_0_len, get_rows_q8_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1564. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl", get_rows_iq4_nl_len, get_rows_iq4_nl_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1565. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F32 ], "get_rows_f32_f32", get_rows_f32_f32_len, get_rows_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  1566. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F16 ], "get_rows_f16_f32", get_rows_f16_f32_len, get_rows_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  1567. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_0], "get_rows_q4_0_f32", get_rows_q4_0_f32_len, get_rows_q4_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1568. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_1], "get_rows_q4_1_f32", get_rows_q4_1_f32_len, get_rows_q4_1_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1569. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_0], "get_rows_q5_0_f32", get_rows_q5_0_f32_len, get_rows_q5_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1570. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_1], "get_rows_q5_1_f32", get_rows_q5_1_f32_len, get_rows_q5_1_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1571. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q8_0], "get_rows_q8_0_f32", get_rows_q8_0_f32_len, get_rows_q8_0_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1572. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl_f32", get_rows_iq4_nl_f32_len, get_rows_iq4_nl_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  1573. ggml_vk_create_pipeline(device, device->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1);
  1574. ggml_vk_create_pipeline(device, 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);
  1575. ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", 3, 7 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  1576. ggml_vk_create_pipeline(device, device->pipeline_norm_f32, "norm_f32", norm_f32_len, norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  1577. ggml_vk_create_pipeline(device, device->pipeline_group_norm_f32, "group_norm_f32", group_norm_f32_len, group_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  1578. ggml_vk_create_pipeline(device, 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);
  1579. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f32, "cpy_f32_f32", cpy_f32_f32_len, cpy_f32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1580. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_f16, "cpy_f32_f16", cpy_f32_f16_len, cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1581. ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f16, "cpy_f16_f16", cpy_f16_f16_len, cpy_f16_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1582. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f32, "contig_cpy_f32_f32", contig_cpy_f32_f32_len, contig_cpy_f32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1583. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_f16, "contig_cpy_f32_f16", contig_cpy_f32_f16_len, contig_cpy_f32_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1584. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f16, "contig_cpy_f16_f16", contig_cpy_f16_f16_len, contig_cpy_f16_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1585. ggml_vk_create_pipeline(device, device->pipeline_add_f32, "add_f32", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1586. ggml_vk_create_pipeline(device, device->pipeline_add_f32_norepeat, "add_f32_norepeat", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1587. ggml_vk_create_pipeline(device, device->pipeline_add_f16_f32_f16, "add_f16_f32_f16", add_f16_f32_f16_len, add_f16_f32_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1588. ggml_vk_create_pipeline(device, device->pipeline_add_f16_f32_f16_norepeat, "add_f16_f32_f16_norepeat", add_f16_f32_f16_len, add_f16_f32_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1589. ggml_vk_create_pipeline(device, device->pipeline_acc_f32, "acc_f32", acc_f32_len, acc_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  1590. ggml_vk_create_pipeline(device, device->pipeline_mul_f32, "mul_f32", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1591. ggml_vk_create_pipeline(device, device->pipeline_mul_f32_norepeat, "mul_f32_norepeat", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1592. ggml_vk_create_pipeline(device, device->pipeline_div_f32, "div_f32", div_f32_len, div_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1593. ggml_vk_create_pipeline(device, device->pipeline_div_f32_norepeat, "div_f32_norepeat", div_f32_len, div_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1594. ggml_vk_create_pipeline(device, device->pipeline_concat_f32, "concat_f32", concat_f32_len, concat_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  1595. ggml_vk_create_pipeline(device, device->pipeline_concat_f16, "concat_f16", concat_f16_len, concat_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  1596. ggml_vk_create_pipeline(device, device->pipeline_concat_i32, "concat_i32", concat_i32_len, concat_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  1597. ggml_vk_create_pipeline(device, device->pipeline_upscale_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {}, 1);
  1598. ggml_vk_create_pipeline(device, device->pipeline_scale_f32, "scale_f32", scale_f32_len, scale_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1599. ggml_vk_create_pipeline(device, device->pipeline_sqr_f32, "sqr_f32", sqr_f32_len, sqr_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1600. ggml_vk_create_pipeline(device, device->pipeline_sin_f32, "sin_f32", sin_f32_len, sin_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1601. ggml_vk_create_pipeline(device, device->pipeline_cos_f32, "cos_f32", cos_f32_len, cos_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1602. ggml_vk_create_pipeline(device, device->pipeline_clamp_f32, "clamp_f32", clamp_f32_len, clamp_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1603. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1604. ggml_vk_create_pipeline(device, device->pipeline_repeat_f32, "repeat_f32", repeat_f32_len, repeat_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1605. ggml_vk_create_pipeline(device, device->pipeline_gelu_f32, "gelu_f32", gelu_f32_len, gelu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1606. ggml_vk_create_pipeline(device, device->pipeline_gelu_quick_f32, "gelu_quick_f32", gelu_quick_f32_len, gelu_quick_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1607. ggml_vk_create_pipeline(device, device->pipeline_silu_f32, "silu_f32", silu_f32_len, silu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1608. ggml_vk_create_pipeline(device, device->pipeline_relu_f32, "relu_f32", relu_f32_len, relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1609. ggml_vk_create_pipeline(device, device->pipeline_leaky_relu_f32, "leaky_relu_f32", leaky_relu_f32_len, leaky_relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1610. ggml_vk_create_pipeline(device, device->pipeline_tanh_f32, "tanh_f32", tanh_f32_len, tanh_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1611. ggml_vk_create_pipeline(device, device->pipeline_diag_mask_inf_f32, "diag_mask_inf_f32", diag_mask_inf_f32_len, diag_mask_inf_f32_data, "main", 2, sizeof(vk_op_diag_mask_push_constants), {512, 1, 1}, {}, 1);
  1612. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1613. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  1614. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1615. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  1616. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1617. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1618. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1619. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1620. ggml_vk_create_pipeline(device, device->pipeline_argsort_f32, "argsort_f32", argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1024, 1, 1}, {}, 1);
  1621. ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1622. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32_len, im2col_f32_data, "main", 2, sizeof(vk_op_im2col_push_constants), {256, 1, 1}, {}, 1);
  1623. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_len, im2col_f32_f16_data, "main", 2, sizeof(vk_op_im2col_push_constants), {256, 1, 1}, {}, 1);
  1624. ggml_vk_create_pipeline(device, device->pipeline_timestep_embedding_f32, "timestep_embedding_f32", timestep_embedding_f32_len, timestep_embedding_f32_data, "main", 2, sizeof(vk_op_timestep_embedding_push_constants), {256, 1, 1}, {}, 1);
  1625. ggml_vk_create_pipeline(device, device->pipeline_pool2d_f32, "pool2d_f32", pool2d_f32_len, pool2d_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {512, 1, 1}, {}, 1);
  1626. for (auto &c : compiles) {
  1627. c.wait();
  1628. }
  1629. std::cerr << "Done!" << std::endl;
  1630. }
  1631. static vk_device ggml_vk_get_device(size_t idx) {
  1632. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  1633. if (vk_instance.devices[idx] == nullptr) {
  1634. VK_LOG_DEBUG("Initializing new vk_device");
  1635. vk_device device = std::make_shared<vk_device_struct>();
  1636. vk_instance.devices[idx] = device;
  1637. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1638. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  1639. #endif
  1640. #ifdef GGML_VULKAN_PERF
  1641. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  1642. #endif
  1643. size_t dev_num = vk_instance.device_indices[idx];
  1644. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  1645. if (dev_num >= physical_devices.size()) {
  1646. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  1647. throw std::runtime_error("Device not found");
  1648. }
  1649. device->physical_device = physical_devices[dev_num];
  1650. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  1651. bool fp16_storage = false;
  1652. bool fp16_compute = false;
  1653. bool maintenance4_support = false;
  1654. bool sm_builtins = false;
  1655. bool amd_shader_core_properties2 = false;
  1656. bool pipeline_robustness = false;
  1657. bool coopmat2_support = false;
  1658. device->coopmat_support = false;
  1659. // Check if maintenance4 is supported
  1660. for (const auto& properties : ext_props) {
  1661. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  1662. maintenance4_support = true;
  1663. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  1664. fp16_storage = true;
  1665. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  1666. fp16_compute = true;
  1667. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  1668. sm_builtins = true;
  1669. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  1670. amd_shader_core_properties2 = true;
  1671. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  1672. pipeline_robustness = true;
  1673. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  1674. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  1675. device->coopmat_support = true;
  1676. device->coopmat_m = 0;
  1677. device->coopmat_n = 0;
  1678. device->coopmat_k = 0;
  1679. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  1680. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  1681. coopmat2_support = true;
  1682. }
  1683. }
  1684. vk::PhysicalDeviceProperties2 props2;
  1685. vk::PhysicalDeviceMaintenance3Properties props3;
  1686. vk::PhysicalDeviceMaintenance4Properties props4;
  1687. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  1688. vk::PhysicalDeviceDriverProperties driver_props;
  1689. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  1690. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  1691. props2.pNext = &props3;
  1692. props3.pNext = &subgroup_props;
  1693. subgroup_props.pNext = &driver_props;
  1694. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  1695. if (maintenance4_support) {
  1696. last_struct->pNext = (VkBaseOutStructure *)&props4;
  1697. last_struct = (VkBaseOutStructure *)&props4;
  1698. }
  1699. if (sm_builtins) {
  1700. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  1701. last_struct = (VkBaseOutStructure *)&sm_props;
  1702. }
  1703. if (amd_shader_core_properties2) {
  1704. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  1705. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  1706. }
  1707. #if defined(VK_NV_cooperative_matrix2)
  1708. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  1709. if (coopmat2_support) {
  1710. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  1711. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  1712. }
  1713. #endif
  1714. device->physical_device.getProperties2(&props2);
  1715. device->properties = props2.properties;
  1716. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  1717. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  1718. device->max_memory_allocation_size = std::stoul(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  1719. } else if (maintenance4_support) {
  1720. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  1721. } else {
  1722. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  1723. }
  1724. device->vendor_id = device->properties.vendorID;
  1725. device->subgroup_size = subgroup_props.subgroupSize;
  1726. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  1727. if (sm_builtins) {
  1728. device->shader_core_count = sm_props.shaderSMCount;
  1729. } else if (amd_shader_core_properties2) {
  1730. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  1731. } else {
  1732. device->shader_core_count = 0;
  1733. }
  1734. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  1735. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  1736. if (device->vendor_id == VK_VENDOR_ID_INTEL || (props2.properties.vendorID == VK_VENDOR_ID_AMD && driver_props.driverID == vk::DriverId::eAmdProprietary)) {
  1737. // Intel drivers don't support coopmat properly yet
  1738. // Only RADV supports coopmat properly on AMD
  1739. device->coopmat_support = false;
  1740. }
  1741. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  1742. // Try to find a non-graphics compute queue and transfer-focused queues
  1743. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  1744. 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);
  1745. const float priorities[] = { 1.0f, 1.0f };
  1746. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  1747. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  1748. if (compute_queue_family_index != transfer_queue_family_index) {
  1749. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1750. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  1751. } else if(!device->single_queue) {
  1752. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  1753. } else {
  1754. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1755. }
  1756. vk::DeviceCreateInfo device_create_info;
  1757. std::vector<const char *> device_extensions;
  1758. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  1759. VkPhysicalDeviceFeatures2 device_features2;
  1760. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  1761. device_features2.pNext = nullptr;
  1762. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  1763. VkPhysicalDeviceVulkan11Features vk11_features;
  1764. vk11_features.pNext = nullptr;
  1765. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  1766. device_features2.pNext = &vk11_features;
  1767. VkPhysicalDeviceVulkan12Features vk12_features;
  1768. vk12_features.pNext = nullptr;
  1769. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  1770. vk11_features.pNext = &vk12_features;
  1771. last_struct = (VkBaseOutStructure *)&vk12_features;
  1772. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  1773. pl_robustness_features.pNext = nullptr;
  1774. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  1775. pl_robustness_features.pipelineRobustness = VK_FALSE;
  1776. if (pipeline_robustness) {
  1777. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  1778. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  1779. device_extensions.push_back("VK_EXT_pipeline_robustness");
  1780. }
  1781. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  1782. coopmat_features.pNext = nullptr;
  1783. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  1784. coopmat_features.cooperativeMatrix = VK_FALSE;
  1785. if (device->coopmat_support) {
  1786. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  1787. last_struct = (VkBaseOutStructure *)&coopmat_features;
  1788. }
  1789. #if defined(VK_NV_cooperative_matrix2)
  1790. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  1791. coopmat2_features.pNext = nullptr;
  1792. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  1793. if (coopmat2_support) {
  1794. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  1795. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  1796. device_extensions.push_back("VK_NV_cooperative_matrix2");
  1797. }
  1798. #endif
  1799. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  1800. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  1801. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  1802. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  1803. if (coopmat2_support) {
  1804. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1805. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  1806. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  1807. coopmat2_features.cooperativeMatrixReductions &&
  1808. coopmat2_features.cooperativeMatrixConversions &&
  1809. coopmat2_features.cooperativeMatrixPerElementOperations &&
  1810. coopmat2_features.cooperativeMatrixTensorAddressing &&
  1811. coopmat2_features.cooperativeMatrixBlockLoads &&
  1812. vk12_features.bufferDeviceAddress) {
  1813. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  1814. uint32_t count = 0;
  1815. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  1816. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  1817. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  1818. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  1819. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  1820. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  1821. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  1822. flexible_dimensions.resize(count, empty_prop);
  1823. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  1824. bool found_fp16_128 = false,
  1825. found_fp16_256 = false,
  1826. found_fp32_128 = false,
  1827. found_fp32_256 = false;
  1828. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  1829. // with 32x16x16 and 256 with 32x32x16.
  1830. for (auto &prop : flexible_dimensions) {
  1831. if (prop.saturatingAccumulation == VK_FALSE &&
  1832. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  1833. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1834. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1835. if (prop.workgroupInvocations == 128 &&
  1836. prop.MGranularity <= 32 &&
  1837. prop.NGranularity <= 16 &&
  1838. prop.KGranularity <= 16) {
  1839. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1840. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1841. found_fp16_128 = true;
  1842. }
  1843. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  1844. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  1845. found_fp32_128 = true;
  1846. }
  1847. }
  1848. if (prop.workgroupInvocations == 256 &&
  1849. prop.MGranularity <= 32 &&
  1850. prop.NGranularity <= 32 &&
  1851. prop.KGranularity <= 16) {
  1852. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1853. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1854. found_fp16_256 = true;
  1855. }
  1856. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  1857. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  1858. found_fp32_256 = true;
  1859. }
  1860. }
  1861. }
  1862. }
  1863. if (found_fp16_128 && found_fp16_256 &&
  1864. found_fp32_128 && found_fp32_256 &&
  1865. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  1866. device->coopmat2 = true;
  1867. }
  1868. }
  1869. #endif
  1870. }
  1871. if (!vk11_features.storageBuffer16BitAccess) {
  1872. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  1873. throw std::runtime_error("Unsupported device");
  1874. }
  1875. device_extensions.push_back("VK_KHR_16bit_storage");
  1876. #ifdef GGML_VULKAN_VALIDATE
  1877. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  1878. #endif
  1879. if (device->fp16) {
  1880. device_extensions.push_back("VK_KHR_shader_float16_int8");
  1881. }
  1882. if (device->coopmat_support) {
  1883. // Query supported shapes
  1884. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  1885. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  1886. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  1887. uint32_t cm_props_num;
  1888. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  1889. cm_props.resize(cm_props_num);
  1890. for (auto& prop : cm_props) {
  1891. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  1892. }
  1893. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  1894. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  1895. for (auto& prop : cm_props) {
  1896. VK_LOG_DEBUG("ggml_vulkan: M: " << prop.MSize << " N: " << prop.NSize << " K: " << prop.KSize << " A: " << vk::to_string((vk::ComponentTypeKHR)prop.AType) << " B: " << vk::to_string((vk::ComponentTypeKHR)prop.BType) << " C: " << vk::to_string((vk::ComponentTypeKHR)prop.CType) << " Result: " << vk::to_string((vk::ComponentTypeKHR)prop.ResultType) << " saturatingAccumulation: " << prop.saturatingAccumulation << " scope: " << vk::to_string((vk::ScopeKHR)prop.scope));
  1897. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  1898. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  1899. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  1900. ) {
  1901. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  1902. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  1903. // coopmat sizes not set yet
  1904. if (device->coopmat_m == 0) {
  1905. device->coopmat_acc_f32_support = true;
  1906. device->coopmat_m = prop.MSize;
  1907. device->coopmat_n = prop.NSize;
  1908. device->coopmat_k = prop.KSize;
  1909. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  1910. // Only enable if shape is identical
  1911. device->coopmat_acc_f32_support = true;
  1912. }
  1913. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  1914. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  1915. // coopmat sizes not set yet
  1916. if (device->coopmat_m == 0) {
  1917. device->coopmat_acc_f16_support = true;
  1918. device->coopmat_m = prop.MSize;
  1919. device->coopmat_n = prop.NSize;
  1920. device->coopmat_k = prop.KSize;
  1921. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  1922. // Only enable if shape is identical
  1923. device->coopmat_acc_f16_support = true;
  1924. }
  1925. }
  1926. }
  1927. }
  1928. if (device->coopmat_m == 0) {
  1929. // No suitable matmul mode found
  1930. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  1931. device->coopmat_support = false;
  1932. }
  1933. }
  1934. if (device->coopmat_support) {
  1935. device_extensions.push_back("VK_KHR_cooperative_matrix");
  1936. }
  1937. device->name = GGML_VK_NAME + std::to_string(idx);
  1938. device_create_info = {
  1939. vk::DeviceCreateFlags(),
  1940. device_queue_create_infos,
  1941. {},
  1942. device_extensions
  1943. };
  1944. device_create_info.setPNext(&device_features2);
  1945. device->device = device->physical_device.createDevice(device_create_info);
  1946. // Queues
  1947. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  1948. // Shaders
  1949. // Disable matmul tile sizes early if performance low or not supported
  1950. switch (device->vendor_id) {
  1951. #ifndef GGML_VULKAN_RUN_TESTS
  1952. case VK_VENDOR_ID_AMD:
  1953. case VK_VENDOR_ID_INTEL:
  1954. device->mul_mat_l = false;
  1955. device->mul_mat_m = true;
  1956. device->mul_mat_s = true;
  1957. device->mul_mat_id_l = false;
  1958. device->mul_mat_id_m = true;
  1959. device->mul_mat_id_s = true;
  1960. break;
  1961. case VK_VENDOR_ID_APPLE:
  1962. device->mul_mat_l = false;
  1963. device->mul_mat_m = true;
  1964. device->mul_mat_s = false;
  1965. device->mul_mat_id_l = false;
  1966. device->mul_mat_id_m = true;
  1967. device->mul_mat_id_s = false;
  1968. break;
  1969. #endif
  1970. default:
  1971. device->mul_mat_l = true;
  1972. device->mul_mat_m = true;
  1973. device->mul_mat_s = true;
  1974. device->mul_mat_id_l = true;
  1975. device->mul_mat_id_m = true;
  1976. device->mul_mat_id_s = true;
  1977. break;
  1978. }
  1979. ggml_vk_load_shaders(device);
  1980. if (!device->single_queue) {
  1981. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  1982. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  1983. } else {
  1984. // TODO: Use pointer or reference to avoid copy
  1985. device->transfer_queue = device->compute_queue;
  1986. }
  1987. device->buffer_type = {
  1988. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  1989. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  1990. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  1991. };
  1992. device->fence = device->device.createFence({});
  1993. device->idx = idx;
  1994. return device;
  1995. }
  1996. return vk_instance.devices[idx];
  1997. }
  1998. static void ggml_vk_print_gpu_info(size_t idx) {
  1999. GGML_ASSERT(idx < vk_instance.device_indices.size());
  2000. size_t dev_num = vk_instance.device_indices[idx];
  2001. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  2002. GGML_ASSERT(vk_instance_initialized);
  2003. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  2004. if (dev_num >= devices.size()) {
  2005. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  2006. throw std::runtime_error("Device not found");
  2007. }
  2008. vk::PhysicalDevice physical_device = devices[dev_num];
  2009. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  2010. vk::PhysicalDeviceProperties2 props2;
  2011. vk::PhysicalDeviceMaintenance3Properties props3;
  2012. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  2013. vk::PhysicalDeviceDriverProperties driver_props;
  2014. props2.pNext = &props3;
  2015. props3.pNext = &subgroup_props;
  2016. subgroup_props.pNext = &driver_props;
  2017. physical_device.getProperties2(&props2);
  2018. const size_t subgroup_size = subgroup_props.subgroupSize;
  2019. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  2020. bool fp16_storage = false;
  2021. bool fp16_compute = false;
  2022. bool coopmat_support = false;
  2023. bool coopmat2_support = false;
  2024. for (auto properties : ext_props) {
  2025. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  2026. fp16_storage = true;
  2027. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  2028. fp16_compute = true;
  2029. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  2030. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  2031. coopmat_support = true;
  2032. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  2033. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  2034. coopmat2_support = true;
  2035. }
  2036. }
  2037. if (props2.properties.vendorID == VK_VENDOR_ID_INTEL || (props2.properties.vendorID == VK_VENDOR_ID_AMD && driver_props.driverID == vk::DriverId::eAmdProprietary)) {
  2038. // Intel drivers don't support coopmat properly yet
  2039. // Only RADV supports coopmat properly on AMD
  2040. coopmat_support = false;
  2041. }
  2042. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  2043. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  2044. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  2045. vk::PhysicalDeviceFeatures device_features = physical_device.getFeatures();
  2046. VkPhysicalDeviceFeatures2 device_features2;
  2047. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  2048. device_features2.pNext = nullptr;
  2049. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  2050. VkPhysicalDeviceVulkan11Features vk11_features;
  2051. vk11_features.pNext = nullptr;
  2052. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  2053. device_features2.pNext = &vk11_features;
  2054. VkPhysicalDeviceVulkan12Features vk12_features;
  2055. vk12_features.pNext = nullptr;
  2056. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  2057. vk11_features.pNext = &vk12_features;
  2058. // Pointer to the last chain element
  2059. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_features;
  2060. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  2061. coopmat_features.pNext = nullptr;
  2062. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  2063. coopmat_features.cooperativeMatrix = VK_FALSE;
  2064. if (coopmat_support) {
  2065. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  2066. last_struct = (VkBaseOutStructure *)&coopmat_features;
  2067. }
  2068. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  2069. fp16 = fp16 && vk12_features.shaderFloat16;
  2070. coopmat_support = coopmat_support && coopmat_features.cooperativeMatrix;
  2071. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  2072. std::string device_name = props2.properties.deviceName.data();
  2073. GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %d | warp size: %zu | matrix cores: %s\n",
  2074. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, subgroup_size, matrix_cores.c_str());
  2075. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  2076. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  2077. }
  2078. }
  2079. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  2080. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  2081. void ggml_vk_instance_init() {
  2082. if (vk_instance_initialized) {
  2083. return;
  2084. }
  2085. VK_LOG_DEBUG("ggml_vk_instance_init()");
  2086. vk_instance_initialized = true;
  2087. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, VK_API_VERSION };
  2088. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  2089. const bool validation_ext = ggml_vk_instance_validation_ext_available(instance_extensions);
  2090. #ifdef __APPLE__
  2091. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  2092. #endif
  2093. std::vector<const char*> layers;
  2094. if (validation_ext) {
  2095. layers.push_back("VK_LAYER_KHRONOS_validation");
  2096. }
  2097. std::vector<const char*> extensions;
  2098. if (validation_ext) {
  2099. extensions.push_back("VK_EXT_validation_features");
  2100. }
  2101. #ifdef __APPLE__
  2102. if (portability_enumeration_ext) {
  2103. extensions.push_back("VK_KHR_portability_enumeration");
  2104. }
  2105. #endif
  2106. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  2107. #ifdef __APPLE__
  2108. if (portability_enumeration_ext) {
  2109. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  2110. }
  2111. #endif
  2112. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  2113. vk::ValidationFeaturesEXT validation_features;
  2114. if (validation_ext) {
  2115. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  2116. validation_features = {
  2117. features_enable,
  2118. {},
  2119. };
  2120. validation_features.setPNext(nullptr);
  2121. instance_create_info.setPNext(&validation_features);
  2122. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  2123. }
  2124. vk_instance.instance = vk::createInstance(instance_create_info);
  2125. size_t num_available_devices = vk_instance.instance.enumeratePhysicalDevices().size();
  2126. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  2127. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  2128. if (devices_env != nullptr) {
  2129. std::string devices(devices_env);
  2130. std::replace(devices.begin(), devices.end(), ',', ' ');
  2131. std::stringstream ss(devices);
  2132. size_t tmp;
  2133. while (ss >> tmp) {
  2134. if(tmp >= num_available_devices) {
  2135. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  2136. throw std::runtime_error("Invalid Vulkan device index");
  2137. }
  2138. vk_instance.device_indices.push_back(tmp);
  2139. }
  2140. } else {
  2141. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  2142. // Make sure at least one device exists
  2143. if (devices.empty()) {
  2144. std::cerr << "ggml_vulkan: Error: No devices found." << std::endl;
  2145. GGML_ABORT("fatal error");
  2146. }
  2147. // Default to using all dedicated GPUs
  2148. for (size_t i = 0; i < devices.size(); i++) {
  2149. vk::PhysicalDeviceProperties2 new_props;
  2150. vk::PhysicalDeviceDriverProperties new_driver;
  2151. vk::PhysicalDeviceIDProperties new_id;
  2152. new_props.pNext = &new_driver;
  2153. new_driver.pNext = &new_id;
  2154. devices[i].getProperties2(&new_props);
  2155. if (new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
  2156. // Check if there are two physical devices corresponding to the same GPU
  2157. auto old_device = std::find_if(
  2158. vk_instance.device_indices.begin(),
  2159. vk_instance.device_indices.end(),
  2160. [&devices, &new_id](const size_t k){
  2161. vk::PhysicalDeviceProperties2 old_props;
  2162. vk::PhysicalDeviceIDProperties old_id;
  2163. old_props.pNext = &old_id;
  2164. devices[k].getProperties2(&old_props);
  2165. return std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  2166. }
  2167. );
  2168. if (old_device == vk_instance.device_indices.end()) {
  2169. vk_instance.device_indices.push_back(i);
  2170. } else {
  2171. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  2172. // This can cause error when splitting layers aross the devices, need to keep only 1
  2173. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  2174. vk::PhysicalDeviceProperties2 old_props;
  2175. vk::PhysicalDeviceDriverProperties old_driver;
  2176. old_props.pNext = &old_driver;
  2177. devices[*old_device].getProperties2(&old_props);
  2178. std::map<vk::DriverId, int> driver_priorities {};
  2179. int old_priority = std::numeric_limits<int>::max();
  2180. int new_priority = std::numeric_limits<int>::max();
  2181. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  2182. // Smaller number -> higher priority
  2183. switch (old_props.properties.vendorID) {
  2184. case VK_VENDOR_ID_AMD:
  2185. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  2186. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  2187. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  2188. break;
  2189. case VK_VENDOR_ID_INTEL:
  2190. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  2191. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  2192. break;
  2193. case VK_VENDOR_ID_NVIDIA:
  2194. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  2195. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  2196. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  2197. #endif
  2198. break;
  2199. }
  2200. if (driver_priorities.count(old_driver.driverID)) {
  2201. old_priority = driver_priorities[old_driver.driverID];
  2202. }
  2203. if (driver_priorities.count(new_driver.driverID)) {
  2204. new_priority = driver_priorities[new_driver.driverID];
  2205. }
  2206. if (new_priority < old_priority) {
  2207. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  2208. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  2209. vk_instance.device_indices.push_back(i);
  2210. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  2211. }
  2212. else {
  2213. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  2214. }
  2215. }
  2216. }
  2217. }
  2218. // If no dedicated GPUs found, fall back to GPU 0
  2219. if (vk_instance.device_indices.empty()) {
  2220. vk_instance.device_indices.push_back(0);
  2221. }
  2222. }
  2223. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  2224. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  2225. ggml_vk_print_gpu_info(i);
  2226. }
  2227. }
  2228. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  2229. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  2230. ggml_vk_instance_init();
  2231. GGML_ASSERT(idx < vk_instance.device_indices.size());
  2232. ctx->name = GGML_VK_NAME + std::to_string(idx);
  2233. ctx->device = ggml_vk_get_device(idx);
  2234. ctx->semaphore_idx = 0;
  2235. ctx->event_idx = 0;
  2236. ctx->prealloc_size_x = 0;
  2237. ctx->prealloc_size_y = 0;
  2238. ctx->prealloc_size_split_k = 0;
  2239. ctx->fence = ctx->device->device.createFence({});
  2240. #ifdef GGML_VULKAN_CHECK_RESULTS
  2241. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  2242. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  2243. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  2244. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  2245. #endif
  2246. }
  2247. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  2248. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  2249. switch (type) {
  2250. case GGML_TYPE_F32:
  2251. case GGML_TYPE_Q4_0:
  2252. case GGML_TYPE_Q4_1:
  2253. case GGML_TYPE_Q5_0:
  2254. case GGML_TYPE_Q5_1:
  2255. case GGML_TYPE_Q8_0:
  2256. case GGML_TYPE_Q2_K:
  2257. case GGML_TYPE_Q3_K:
  2258. case GGML_TYPE_Q4_K:
  2259. case GGML_TYPE_Q5_K:
  2260. case GGML_TYPE_Q6_K:
  2261. case GGML_TYPE_IQ4_NL:
  2262. break;
  2263. default:
  2264. return nullptr;
  2265. }
  2266. return ctx->device->pipeline_dequant[type];
  2267. }
  2268. static vk_matmul_pipeline ggml_vk_get_mul_mat_mat_pipeline(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec) {
  2269. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  2270. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2271. return ctx->device->pipeline_matmul_f32;
  2272. }
  2273. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  2274. return ctx->device->pipeline_matmul_f32_f16;
  2275. }
  2276. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16) {
  2277. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2278. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  2279. }
  2280. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2281. return ctx->device->pipeline_matmul_f16.f16acc;
  2282. }
  2283. } else {
  2284. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2285. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  2286. }
  2287. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2288. return ctx->device->pipeline_matmul_f16.f32acc;
  2289. }
  2290. }
  2291. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  2292. return nullptr;
  2293. }
  2294. switch (src0_type) {
  2295. case GGML_TYPE_Q4_0:
  2296. case GGML_TYPE_Q4_1:
  2297. case GGML_TYPE_Q5_0:
  2298. case GGML_TYPE_Q5_1:
  2299. case GGML_TYPE_Q8_0:
  2300. case GGML_TYPE_Q2_K:
  2301. case GGML_TYPE_Q3_K:
  2302. case GGML_TYPE_Q4_K:
  2303. case GGML_TYPE_Q5_K:
  2304. case GGML_TYPE_Q6_K:
  2305. case GGML_TYPE_IQ4_NL:
  2306. break;
  2307. default:
  2308. return nullptr;
  2309. }
  2310. if (ctx->device->coopmat2) {
  2311. assert(src1_type == GGML_TYPE_F16);
  2312. return ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f16acc;
  2313. }
  2314. return ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  2315. }
  2316. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  2317. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  2318. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16);
  2319. switch (a_type) {
  2320. case GGML_TYPE_F32:
  2321. case GGML_TYPE_F16:
  2322. case GGML_TYPE_Q4_0:
  2323. case GGML_TYPE_Q4_1:
  2324. case GGML_TYPE_Q5_0:
  2325. case GGML_TYPE_Q5_1:
  2326. case GGML_TYPE_Q8_0:
  2327. case GGML_TYPE_Q2_K:
  2328. case GGML_TYPE_Q3_K:
  2329. case GGML_TYPE_Q4_K:
  2330. case GGML_TYPE_Q5_K:
  2331. case GGML_TYPE_Q6_K:
  2332. case GGML_TYPE_IQ4_NL:
  2333. break;
  2334. default:
  2335. return nullptr;
  2336. }
  2337. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[a_type] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[a_type];
  2338. }
  2339. static vk_matmul_pipeline ggml_vk_get_mul_mat_mat_id_pipeline(ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec) {
  2340. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  2341. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2342. return ctx->device->pipeline_matmul_id_f32;
  2343. }
  2344. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16) {
  2345. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2346. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  2347. }
  2348. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2349. return ctx->device->pipeline_matmul_id_f16.f16acc;
  2350. }
  2351. } else {
  2352. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2353. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  2354. }
  2355. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2356. return ctx->device->pipeline_matmul_id_f16.f32acc;
  2357. }
  2358. }
  2359. GGML_ASSERT(src1_type == GGML_TYPE_F32);
  2360. switch (src0_type) {
  2361. case GGML_TYPE_Q4_0:
  2362. case GGML_TYPE_Q4_1:
  2363. case GGML_TYPE_Q5_0:
  2364. case GGML_TYPE_Q5_1:
  2365. case GGML_TYPE_Q8_0:
  2366. case GGML_TYPE_Q2_K:
  2367. case GGML_TYPE_Q3_K:
  2368. case GGML_TYPE_Q4_K:
  2369. case GGML_TYPE_Q5_K:
  2370. case GGML_TYPE_Q6_K:
  2371. case GGML_TYPE_IQ4_NL:
  2372. break;
  2373. default:
  2374. return nullptr;
  2375. }
  2376. return ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc;
  2377. }
  2378. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  2379. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  2380. GGML_ASSERT(b_type == GGML_TYPE_F32);
  2381. switch (a_type) {
  2382. case GGML_TYPE_F32:
  2383. case GGML_TYPE_F16:
  2384. case GGML_TYPE_Q4_0:
  2385. case GGML_TYPE_Q4_1:
  2386. case GGML_TYPE_Q5_0:
  2387. case GGML_TYPE_Q5_1:
  2388. case GGML_TYPE_Q8_0:
  2389. case GGML_TYPE_Q2_K:
  2390. case GGML_TYPE_Q3_K:
  2391. case GGML_TYPE_Q4_K:
  2392. case GGML_TYPE_Q5_K:
  2393. case GGML_TYPE_Q6_K:
  2394. case GGML_TYPE_IQ4_NL:
  2395. break;
  2396. default:
  2397. return nullptr;
  2398. }
  2399. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  2400. }
  2401. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  2402. VK_LOG_DEBUG("ggml_vk_pool_malloc(" << size << ")");
  2403. VK_LOG_MEMORY("ggml_vk_pool_malloc");
  2404. int best_i = -1;
  2405. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  2406. int worst_i = -1;
  2407. size_t worst_size = 0; //largest unused buffer seen so far
  2408. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  2409. vk_buffer &b = ctx->buffer_pool[i];
  2410. if (b != nullptr && b->size >= size && b->size < best_size) {
  2411. best_i = i;
  2412. best_size = b->size;
  2413. }
  2414. if (b != nullptr && b->size > worst_size) {
  2415. worst_i = i;
  2416. worst_size = b->size;
  2417. }
  2418. }
  2419. if(best_i != -1) {
  2420. //found the smallest buffer that fits our needs
  2421. vk_buffer b = ctx->buffer_pool[best_i];
  2422. ctx->buffer_pool[best_i].reset();
  2423. return b;
  2424. }
  2425. if(worst_i != -1) {
  2426. //no buffer that fits our needs, resize largest one to save memory
  2427. vk_buffer& b = ctx->buffer_pool[worst_i];
  2428. ggml_vk_destroy_buffer(b);
  2429. }
  2430. return ggml_vk_create_buffer_device(ctx->device, size);
  2431. }
  2432. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  2433. VK_LOG_DEBUG("ggml_vk_pool_free(" << buffer->size << ")");
  2434. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  2435. vk_buffer& b = ctx->buffer_pool[i];
  2436. if (b == nullptr) {
  2437. b = buffer;
  2438. return;
  2439. }
  2440. }
  2441. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  2442. ggml_vk_destroy_buffer(buffer);
  2443. }
  2444. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  2445. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  2446. // Try to find existing temp buffer with enough capacity
  2447. for (auto& buffer : ctx->gc.temp_buffers) {
  2448. if (buffer->size >= size) {
  2449. return buffer;
  2450. }
  2451. }
  2452. VK_LOG_MEMORY("ggml_vk_create_buffer_temp(" << size << ")");
  2453. // Otherwise create new buffer
  2454. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  2455. ctx->gc.temp_buffers.push_back(buf);
  2456. return buf;
  2457. }
  2458. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  2459. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  2460. vk_buffer buf = ggml_vk_create_buffer(device, size,
  2461. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  2462. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  2463. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  2464. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  2465. size/1024.0/1024.0);
  2466. device->device.freeMemory(buf->device_memory);
  2467. device->device.destroyBuffer(buf->buffer);
  2468. return nullptr;
  2469. }
  2470. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  2471. return buf->ptr;
  2472. }
  2473. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  2474. if (ptr == nullptr) {
  2475. return;
  2476. }
  2477. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  2478. vk_buffer buf;
  2479. size_t index;
  2480. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  2481. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  2482. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  2483. if (ptr >= addr && ptr < endr) {
  2484. buf = std::get<2>(device->pinned_memory[i]);
  2485. index = i;
  2486. break;
  2487. }
  2488. }
  2489. if (buf == nullptr) {
  2490. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  2491. return;
  2492. }
  2493. ggml_vk_destroy_buffer(buf);
  2494. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  2495. }
  2496. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  2497. buf = nullptr;
  2498. buf_offset = 0;
  2499. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  2500. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  2501. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  2502. if (ptr >= addr && ptr < endr) {
  2503. buf = std::get<2>(device->pinned_memory[i]);
  2504. buf_offset = ((const uint8_t *)ptr) - addr;
  2505. break;
  2506. }
  2507. }
  2508. }
  2509. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_queue& q, bool one_time = true) {
  2510. vk_submission s;
  2511. s.buffer = ggml_vk_create_cmd_buffer(device, q);
  2512. if (one_time) {
  2513. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  2514. } else {
  2515. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  2516. }
  2517. return s;
  2518. }
  2519. static void ggml_vk_dispatch_pipeline(ggml_backend_vk_context* ctx, vk_context& subctx, vk_pipeline& pipeline, std::initializer_list<vk::DescriptorBufferInfo> const& descriptor_buffer_infos, size_t push_constant_size, const void* push_constants, std::array<uint32_t, 3> elements) {
  2520. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  2521. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  2522. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  2523. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  2524. for (auto& buffer : descriptor_buffer_infos) {
  2525. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  2526. }
  2527. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  2528. GGML_ASSERT(pipeline->descriptor_set_idx < pipeline->descriptor_sets.size());
  2529. GGML_ASSERT(descriptor_buffer_infos.size() == pipeline->parameter_count);
  2530. vk::DescriptorSet& descriptor_set = pipeline->descriptor_sets[pipeline->descriptor_set_idx++];
  2531. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  2532. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  2533. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size, push_constants);
  2534. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  2535. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  2536. pipeline->layout,
  2537. 0,
  2538. { descriptor_set },
  2539. {});
  2540. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  2541. }
  2542. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  2543. s.buffer.end();
  2544. s.wait_semaphores = std::move(wait_semaphores);
  2545. s.signal_semaphores = std::move(signal_semaphores);
  2546. }
  2547. static void ggml_vk_ctx_end(vk_context& ctx) {
  2548. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  2549. if (ctx->s == nullptr) {
  2550. return;
  2551. }
  2552. ctx->s->buffer.end();
  2553. ctx->s = nullptr;
  2554. }
  2555. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  2556. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  2557. if (subctx->s != nullptr) {
  2558. ggml_vk_ctx_end(subctx);
  2559. }
  2560. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->q) });
  2561. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  2562. }
  2563. static size_t ggml_vk_align_size(size_t width, size_t align) {
  2564. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  2565. return CEIL_DIV(width, align) * align;
  2566. }
  2567. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  2568. if (memcpys == nullptr) {
  2569. memcpy(dst, src, size);
  2570. } else {
  2571. memcpys->emplace_back(dst, src, size);
  2572. }
  2573. }
  2574. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  2575. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  2576. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  2577. ggml_vk_destroy_buffer(device->sync_staging);
  2578. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  2579. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  2580. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  2581. }
  2582. }
  2583. 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) {
  2584. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  2585. GGML_ASSERT(!ggml_is_contiguous(tensor));
  2586. // Buffer is already mapped
  2587. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2588. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  2589. GGML_ABORT("fatal error");
  2590. }
  2591. // Check if src is pinned memory
  2592. vk_buffer buf;
  2593. size_t buf_offset;
  2594. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  2595. const uint64_t ne0 = tensor->ne[0];
  2596. const uint64_t ne1 = tensor->ne[1];
  2597. const uint64_t ne2 = tensor->ne[2];
  2598. const uint64_t ne3 = tensor->ne[3];
  2599. const uint64_t nb0 = tensor->nb[0];
  2600. const uint64_t nb1 = tensor->nb[1];
  2601. const uint64_t nb2 = tensor->nb[2];
  2602. const uint64_t nb3 = tensor->nb[3];
  2603. const ggml_type type = tensor->type;
  2604. const uint64_t ts = ggml_type_size(type);
  2605. const uint64_t bs = ggml_blck_size(type);
  2606. const uint64_t dstnb0 = ts;
  2607. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  2608. const uint64_t dstnb2 = dstnb1*ne1;
  2609. const uint64_t dstnb3 = dstnb2*ne2;
  2610. const uint64_t ne = ggml_nelements(tensor);
  2611. if (buf != nullptr) {
  2612. // Memory is pinned, use as staging buffer
  2613. std::vector<vk::BufferCopy> slices;
  2614. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  2615. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  2616. // Find longest contiguous slice
  2617. if (ne1*nb1 == dstnb2) {
  2618. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  2619. } else {
  2620. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  2621. if (ne0*nb0/bs == dstnb1) {
  2622. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  2623. } else {
  2624. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  2625. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  2626. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  2627. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  2628. }
  2629. }
  2630. }
  2631. }
  2632. }
  2633. }
  2634. ggml_vk_sync_buffers(subctx);
  2635. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  2636. return;
  2637. }
  2638. if (!sync_staging) {
  2639. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  2640. }
  2641. // Staging buffer required
  2642. vk_buffer& staging = ctx->device->sync_staging;
  2643. const uint64_t copy_size = ts*ne/bs;
  2644. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  2645. VkBufferCopy buf_copy{ 0, offset, copy_size };
  2646. ggml_vk_sync_buffers(subctx);
  2647. vkCmdCopyBuffer(subctx->s->buffer, staging->buffer, dst->buffer, 1, &buf_copy);
  2648. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  2649. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  2650. // Find longest contiguous slice
  2651. if (ne1*nb1 == dstnb2) {
  2652. deferred_memcpy((uint8_t *)staging->ptr + i3*dstnb3 + i2*dstnb2, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2, dstnb2, &subctx->in_memcpys);
  2653. } else {
  2654. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  2655. if (ne0*nb0/bs == dstnb1) {
  2656. deferred_memcpy((uint8_t *)staging->ptr + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, (const uint8_t *) tensor->data + buf_offset + i3*nb3 + i2*nb2 + i1*nb1, dstnb1, &subctx->in_memcpys);
  2657. } else {
  2658. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  2659. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  2660. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  2661. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  2662. }
  2663. }
  2664. }
  2665. }
  2666. }
  2667. }
  2668. }
  2669. static void ggml_vk_buffer_write_2d_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height, bool sync_staging = false) {
  2670. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  2671. // Buffer is already mapped
  2672. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2673. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  2674. GGML_ABORT("fatal error");
  2675. }
  2676. // Check if src is pinned memory
  2677. vk_buffer buf = nullptr;
  2678. size_t buf_offset;
  2679. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  2680. if (buf != nullptr) {
  2681. // Memory is pinned, use as staging buffer
  2682. std::vector<vk::BufferCopy> slices(1);
  2683. if (width == spitch) {
  2684. // Only do single write if stride is equal
  2685. slices[0].srcOffset = buf_offset;
  2686. slices[0].dstOffset = offset;
  2687. slices[0].size = width * height;
  2688. } else {
  2689. slices.resize(height);
  2690. for (size_t i = 0; i < height; i++) {
  2691. slices[i].srcOffset = buf_offset + i * spitch;
  2692. slices[i].dstOffset = offset + i * width;
  2693. slices[i].size = width;
  2694. }
  2695. }
  2696. ggml_vk_sync_buffers(subctx);
  2697. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  2698. return;
  2699. }
  2700. VK_LOG_DEBUG("STAGING");
  2701. if (!sync_staging) {
  2702. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  2703. }
  2704. // Staging buffer required
  2705. const size_t copy_size = width*height;
  2706. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  2707. vk_buffer& staging_buffer = dst->device->sync_staging;
  2708. VkBufferCopy buf_copy = {
  2709. 0,
  2710. offset,
  2711. copy_size};
  2712. ggml_vk_sync_buffers(subctx);
  2713. vkCmdCopyBuffer(subctx->s->buffer, staging_buffer->buffer, dst->buffer, 1, &buf_copy);
  2714. if (width == spitch) {
  2715. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  2716. } else {
  2717. for (size_t i = 0; i < height; i++) {
  2718. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  2719. }
  2720. }
  2721. }
  2722. static void ggml_vk_buffer_write_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  2723. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  2724. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  2725. }
  2726. static void ggml_vk_buffer_write_2d(vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height) {
  2727. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  2728. // Buffer is already mapped
  2729. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2730. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  2731. for (size_t i = 0; i < height; i++) {
  2732. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  2733. }
  2734. } else {
  2735. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue);
  2736. ggml_vk_ctx_begin(dst->device, subctx);
  2737. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  2738. ggml_vk_ctx_end(subctx);
  2739. for (auto& cpy : subctx->in_memcpys) {
  2740. memcpy(cpy.dst, cpy.src, cpy.n);
  2741. }
  2742. ggml_vk_submit(subctx, dst->device->fence);
  2743. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  2744. dst->device->device.resetFences({ dst->device->fence });
  2745. }
  2746. }
  2747. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  2748. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  2749. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  2750. }
  2751. static void ggml_vk_buffer_read_2d_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t spitch, size_t dpitch, size_t width, size_t height, bool sync_staging = false) {
  2752. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  2753. GGML_ASSERT(width > 0);
  2754. GGML_ASSERT(height > 0);
  2755. GGML_ASSERT(src != nullptr);
  2756. // TODO: staging_offset is not used
  2757. // Check if dst is pinned memory
  2758. vk_buffer buf = nullptr;
  2759. size_t buf_offset;
  2760. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  2761. std::vector<vk::BufferCopy> slices(1);
  2762. if (width == spitch && width == dpitch) {
  2763. // Only do single write if stride is equal
  2764. slices[0].srcOffset = offset;
  2765. slices[0].dstOffset = buf_offset;
  2766. slices[0].size = width * height;
  2767. } else {
  2768. slices.resize(height);
  2769. for (size_t i = 0; i < height; i++) {
  2770. slices[i].srcOffset = offset + i * spitch;
  2771. slices[i].dstOffset = buf_offset + i * dpitch;
  2772. slices[i].size = width;
  2773. }
  2774. }
  2775. if (buf != nullptr) {
  2776. // Memory is pinned, use as staging buffer
  2777. ggml_vk_sync_buffers(subctx);
  2778. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  2779. return;
  2780. }
  2781. VK_LOG_DEBUG("STAGING");
  2782. if (!sync_staging) {
  2783. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  2784. }
  2785. // Fall back to staging buffer
  2786. const size_t copy_size = dpitch * height;
  2787. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  2788. vk_buffer& staging_buffer = src->device->sync_staging;
  2789. ggml_vk_sync_buffers(subctx);
  2790. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  2791. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  2792. }
  2793. static void ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  2794. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  2795. }
  2796. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  2797. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  2798. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  2799. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  2800. // the HW device to host copy path.
  2801. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  2802. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  2803. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  2804. } else {
  2805. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue);
  2806. ggml_vk_ctx_begin(src->device, subctx);
  2807. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  2808. ggml_vk_ctx_end(subctx);
  2809. ggml_vk_submit(subctx, src->device->fence);
  2810. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  2811. src->device->device.resetFences({ src->device->fence });
  2812. for (auto& cpy : subctx->out_memcpys) {
  2813. memcpy(cpy.dst, cpy.src, cpy.n);
  2814. }
  2815. }
  2816. }
  2817. 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) {
  2818. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  2819. // Make sure both buffers are on same device
  2820. GGML_ASSERT(src->device == dst->device);
  2821. VkBufferCopy bc{ src_offset, dst_offset, size };
  2822. vkCmdCopyBuffer(ctx->s->buffer, src->buffer, dst->buffer, 1, &bc);
  2823. }
  2824. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  2825. if (src->device == dst->device) {
  2826. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  2827. // Copy within the device
  2828. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue);
  2829. ggml_vk_ctx_begin(src->device, subctx);
  2830. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  2831. ggml_vk_ctx_end(subctx);
  2832. ggml_vk_submit(subctx, src->device->fence);
  2833. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  2834. src->device->device.resetFences({ src->device->fence });
  2835. } else {
  2836. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  2837. // Copy device to device
  2838. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  2839. ggml_vk_ensure_sync_staging_buffer(dst->device, size);
  2840. // Copy to src staging buffer
  2841. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  2842. // memcpy to dst staging buffer
  2843. memcpy(dst->device->sync_staging->ptr, src->device->sync_staging->ptr, size);
  2844. // Copy to dst buffer
  2845. ggml_vk_buffer_copy(dst, dst_offset, dst->device->sync_staging, 0, size);
  2846. }
  2847. }
  2848. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  2849. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  2850. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue);
  2851. ggml_vk_ctx_begin(dst->device, subctx);
  2852. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  2853. ggml_vk_ctx_end(subctx);
  2854. ggml_vk_submit(subctx, dst->device->fence);
  2855. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  2856. dst->device->device.resetFences({ dst->device->fence });
  2857. }
  2858. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, int m, int n, int k, const vk_pipeline& pipeline) {
  2859. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ")");
  2860. uint32_t split_k = 1;
  2861. if (ctx->device->shader_core_count != 0 && m >= (int)pipeline->wg_denoms[0] && n >= (int)pipeline->wg_denoms[1]) {
  2862. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  2863. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  2864. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  2865. if (k >= 2048 && m_tiles * n_tiles < ctx->device->shader_core_count / 2) {
  2866. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  2867. // Clamp to 2 or 4
  2868. split_k = std::min(split_k, 4u);
  2869. if (split_k == 3) {
  2870. split_k = 2;
  2871. }
  2872. }
  2873. }
  2874. return split_k;
  2875. }
  2876. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned, ggml_type type_a) {
  2877. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")");
  2878. if (ctx->device->coopmat2) {
  2879. if ((ctx->device->mul_mat_l && (m % mmp->l->wg_denoms[0]) == 0 && (n % mmp->l->wg_denoms[1]) == 0) || (!ctx->device->mul_mat_m && !ctx->device->mul_mat_s)) {
  2880. return aligned ? mmp->a_l : mmp->l;
  2881. }
  2882. if ((ctx->device->mul_mat_m && (m % mmp->m->wg_denoms[0]) == 0 && (n % mmp->m->wg_denoms[1]) == 0) || !ctx->device->mul_mat_s) {
  2883. return aligned ? mmp->a_m : mmp->m;
  2884. }
  2885. return aligned ? mmp->a_s : mmp->s;
  2886. }
  2887. if ((ctx->device->mul_mat_s && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_m && !ctx->device->mul_mat_l)) {
  2888. return aligned ? mmp->a_s : mmp->s;
  2889. }
  2890. if ((ctx->device->mul_mat_m && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l) {
  2891. return aligned ? mmp->a_m : mmp->m;
  2892. }
  2893. return aligned ? mmp->a_l : mmp->l;
  2894. }
  2895. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type type_a) {
  2896. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")");
  2897. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, type_a)->align;
  2898. }
  2899. static void ggml_vk_matmul(
  2900. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  2901. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  2902. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  2903. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  2904. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3) {
  2905. VK_LOG_DEBUG("ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << (split_k_buffer.buffer != nullptr ? split_k_buffer.buffer->buffer : VK_NULL_HANDLE) << ", " << split_k_buffer.offset << ", " << split_k_buffer.size << "), m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ")");
  2906. ggml_vk_sync_buffers(subctx);
  2907. if (split_k == 1) {
  2908. const vk_mat_mat_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, k, ne02, ne12, broadcast2, broadcast3 };
  2909. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, sizeof(vk_mat_mat_push_constants), &pc, { m, n, batch });
  2910. return;
  2911. }
  2912. GGML_ASSERT(batch_stride_d == m * n);
  2913. const vk_mat_mat_push_constants pc1 = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, CEIL_DIV(k, split_k), ne02, ne12, broadcast2, broadcast3 };
  2914. // Make sure enough workgroups get assigned for split k to work
  2915. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, sizeof(vk_mat_mat_push_constants), &pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  2916. ggml_vk_sync_buffers(subctx);
  2917. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  2918. 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 });
  2919. }
  2920. static vk_pipeline ggml_vk_guess_matmul_id_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  2921. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")");
  2922. if (ctx->device->coopmat2) {
  2923. if ((ctx->device->mul_mat_id_l && (m % mmp->l->wg_denoms[0]) == 0 && (n % mmp->l->wg_denoms[1]) == 0) || (!ctx->device->mul_mat_id_m && !ctx->device->mul_mat_id_s)) {
  2924. return aligned ? mmp->a_l : mmp->l;
  2925. }
  2926. if ((ctx->device->mul_mat_id_m && (m % mmp->m->wg_denoms[0]) == 0 && (n % mmp->m->wg_denoms[1]) == 0) || !ctx->device->mul_mat_id_s) {
  2927. return aligned ? mmp->a_m : mmp->m;
  2928. }
  2929. return aligned ? mmp->a_s : mmp->s;
  2930. }
  2931. if ((ctx->device->mul_mat_id_s && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_id_m && !ctx->device->mul_mat_id_l)) {
  2932. return aligned ? mmp->a_s : mmp->s;
  2933. }
  2934. if ((ctx->device->mul_mat_id_m && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l) {
  2935. return aligned ? mmp->a_m : mmp->m;
  2936. }
  2937. return aligned ? mmp->a_l : mmp->l;
  2938. }
  2939. static uint32_t ggml_vk_guess_matmul_id_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n) {
  2940. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")");
  2941. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true)->align;
  2942. }
  2943. static void ggml_vk_matmul_id(
  2944. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  2945. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  2946. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  2947. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  2948. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11) {
  2949. VK_LOG_DEBUG("ggml_vk_matmul_id(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), ids: (" << ids.buffer->buffer << ", " << ids.offset << ", " << ids.size << "), " <<
  2950. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  2951. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  2952. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  2953. ggml_vk_sync_buffers(subctx);
  2954. const vk_mat_mat_id_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d,
  2955. nei0, nei1, nbi1, ne11 };
  2956. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, sizeof(vk_mat_mat_id_push_constants), &pc, { m, nei1, n_as });
  2957. }
  2958. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  2959. return
  2960. tensor->nb[0] == ggml_type_size(tensor->type) &&
  2961. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  2962. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  2963. }
  2964. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  2965. // Choose "contiguous copy" shader if src/dst are contiguous
  2966. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  2967. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  2968. if (contig) {
  2969. return ctx->device->pipeline_contig_cpy_f32_f32;
  2970. } else {
  2971. return ctx->device->pipeline_cpy_f32_f32;
  2972. }
  2973. }
  2974. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  2975. if (contig) {
  2976. return ctx->device->pipeline_contig_cpy_f32_f16;
  2977. } else {
  2978. return ctx->device->pipeline_cpy_f32_f16;
  2979. }
  2980. }
  2981. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  2982. if (contig) {
  2983. return ctx->device->pipeline_contig_cpy_f16_f16;
  2984. } else {
  2985. return ctx->device->pipeline_cpy_f16_f16;
  2986. }
  2987. }
  2988. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  2989. GGML_ABORT("fatal error");
  2990. }
  2991. 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) {
  2992. VK_LOG_DEBUG("ggml_vk_cpy_to_contiguous((" << tensor << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << "), ";
  2993. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  2994. const int tensor_type_size = ggml_type_size(tensor->type);
  2995. const uint32_t ne = ggml_nelements(tensor);
  2996. std::array<uint32_t, 3> elements;
  2997. if (ne > 262144) {
  2998. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  2999. } else if (ne > 512) {
  3000. elements = { 512, CEIL_DIV(ne, 512), 1 };
  3001. } else {
  3002. elements = { ne, 1, 1 };
  3003. }
  3004. vk_op_unary_push_constants pc = {
  3005. (uint32_t)ne,
  3006. (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,
  3007. (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]),
  3008. 0,
  3009. 0.0f, 0.0f,
  3010. };
  3011. init_pushconst_fastdiv(pc);
  3012. ggml_vk_sync_buffers(subctx);
  3013. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, sizeof(vk_op_unary_push_constants), &pc, elements);
  3014. }
  3015. static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3016. VK_LOG_DEBUG("ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3017. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3018. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3019. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3020. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3021. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3022. const uint64_t ne00 = src0->ne[0];
  3023. const uint64_t ne01 = src0->ne[1];
  3024. const uint64_t ne02 = src0->ne[2];
  3025. const uint64_t ne03 = src0->ne[3];
  3026. const uint64_t ne10 = src1->ne[0];
  3027. const uint64_t ne11 = src1->ne[1];
  3028. const uint64_t ne12 = src1->ne[2];
  3029. const uint64_t ne13 = src1->ne[3];
  3030. const uint64_t ne20 = dst->ne[0];
  3031. const uint64_t ne21 = dst->ne[1];
  3032. const uint64_t r2 = ne12 / ne02;
  3033. const uint64_t r3 = ne13 / ne03;
  3034. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3035. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3036. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3037. vk_buffer d_Qx;
  3038. size_t qx_buf_offset = 0;
  3039. vk_buffer d_Qy;
  3040. size_t qy_buf_offset = 0;
  3041. bool src0_uma = false;
  3042. bool src1_uma = false;
  3043. if (ctx->device->uma) {
  3044. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3045. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3046. src0_uma = d_Qx != nullptr;
  3047. src1_uma = d_Qy != nullptr;
  3048. }
  3049. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3050. // Reformat and convert to fp16 if src1 is non-contiguous, or for coopmat2 for better perf
  3051. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  3052. !ggml_vk_dim01_contiguous(src1);
  3053. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  3054. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type, (ggml_prec)dst->op_params[0]);
  3055. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  3056. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  3057. if (qx_needs_dequant) {
  3058. // Fall back to dequant + f16 mulmat
  3059. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, GGML_TYPE_F16, y_f32_kernel ? GGML_TYPE_F32 : GGML_TYPE_F16, (ggml_prec)dst->op_params[0]);
  3060. }
  3061. // Not implemented
  3062. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3063. const int x_ne = ne01 * ne00;
  3064. const int y_ne = ne11 * ne10;
  3065. const int d_ne = ne11 * ne01;
  3066. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11, src0->type));
  3067. const bool aligned = ne10 == kpad && ne01 > 8 && ne11 > 8;
  3068. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned, src0->type);
  3069. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, pipeline);
  3070. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  3071. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3072. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  3073. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3074. const uint64_t d_sz = sizeof(float) * d_ne;
  3075. vk_pipeline to_fp16_vk_0 = nullptr;
  3076. vk_pipeline to_fp16_vk_1 = nullptr;
  3077. if (x_non_contig) {
  3078. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, GGML_TYPE_F16);
  3079. } else {
  3080. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  3081. }
  3082. if (y_non_contig) {
  3083. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, GGML_TYPE_F16);
  3084. } else {
  3085. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3086. }
  3087. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3088. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3089. if (dryrun) {
  3090. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3091. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3092. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  3093. if (
  3094. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3095. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size) ||
  3096. (split_k > 1 && split_k_size > ctx->device->max_memory_allocation_size)) {
  3097. GGML_ABORT("Requested preallocation size is too large");
  3098. }
  3099. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3100. ctx->prealloc_size_x = x_sz_upd;
  3101. }
  3102. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3103. ctx->prealloc_size_y = y_sz_upd;
  3104. }
  3105. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  3106. ctx->prealloc_size_split_k = split_k_size;
  3107. }
  3108. // Request descriptor sets
  3109. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3110. if (qx_needs_dequant) {
  3111. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3112. }
  3113. if (qy_needs_dequant) {
  3114. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3115. }
  3116. if (split_k > 1) {
  3117. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, 1);
  3118. }
  3119. return;
  3120. }
  3121. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3122. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3123. GGML_ASSERT(d_D != nullptr);
  3124. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  3125. vk_buffer d_X;
  3126. uint64_t x_buf_offset = 0;
  3127. vk_buffer d_Y;
  3128. uint64_t y_buf_offset = 0;
  3129. if (!src0_uma) {
  3130. d_Qx = src0_buf_ctx->dev_buffer;
  3131. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3132. GGML_ASSERT(d_Qx != nullptr);
  3133. }
  3134. if (!src1_uma) {
  3135. d_Qy = src1_buf_ctx->dev_buffer;
  3136. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3137. GGML_ASSERT(d_Qy != nullptr);
  3138. }
  3139. if (qx_needs_dequant) {
  3140. d_X = ctx->prealloc_x;
  3141. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  3142. } else {
  3143. d_X = d_Qx;
  3144. x_buf_offset = qx_buf_offset;
  3145. GGML_ASSERT(qx_sz == x_sz);
  3146. }
  3147. if (qy_needs_dequant) {
  3148. d_Y = ctx->prealloc_y;
  3149. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  3150. } else {
  3151. d_Y = d_Qy;
  3152. y_buf_offset = qy_buf_offset;
  3153. GGML_ASSERT(qy_sz == y_sz);
  3154. }
  3155. if (x_non_contig) {
  3156. 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 });
  3157. } else if (qx_needs_dequant) {
  3158. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  3159. ggml_vk_sync_buffers(subctx);
  3160. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  3161. }
  3162. if (y_non_contig) {
  3163. 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 });
  3164. }
  3165. uint32_t stride_batch_x = ne00*ne01;
  3166. uint32_t stride_batch_y = ne10*ne11;
  3167. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3168. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3169. }
  3170. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3171. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3172. }
  3173. // compute
  3174. ggml_vk_matmul(
  3175. ctx, subctx, pipeline,
  3176. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  3177. { d_D, d_buf_offset, d_sz * ne12 * ne13 }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  3178. ne01, ne11, ne10,
  3179. ne10, ne10, ne01, stride_batch_x, stride_batch_y, ne20*ne21,
  3180. split_k, ne12*ne13, ne02, ne12, r2, r3
  3181. ); // NOLINT
  3182. }
  3183. 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, bool dryrun = false) {
  3184. VK_LOG_DEBUG("ggml_vk_mul_mat_vec_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3185. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3186. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3187. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  3188. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3189. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3190. const uint64_t ne00 = src0->ne[0];
  3191. const uint64_t ne01 = src0->ne[1];
  3192. const uint64_t ne02 = src0->ne[2];
  3193. const uint64_t ne03 = src0->ne[3];
  3194. const uint64_t ne10 = src1->ne[0];
  3195. const uint64_t ne11 = src1->ne[1];
  3196. const uint64_t ne12 = src1->ne[2];
  3197. const uint64_t ne13 = src1->ne[3];
  3198. GGML_ASSERT(ne11 == 1);
  3199. const uint64_t ne20 = dst->ne[0];
  3200. const uint64_t ne21 = dst->ne[1];
  3201. const uint64_t ne22 = dst->ne[2];
  3202. const uint64_t ne23 = dst->ne[3];
  3203. const uint64_t r2 = ne12 / ne02;
  3204. const uint64_t r3 = ne13 / ne03;
  3205. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3206. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3207. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3208. vk_buffer d_Qx;
  3209. size_t qx_buf_offset = 0;
  3210. vk_buffer d_Qy;
  3211. size_t qy_buf_offset = 0;
  3212. bool src0_uma = false;
  3213. bool src1_uma = false;
  3214. if (ctx->device->uma) {
  3215. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3216. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3217. src0_uma = d_Qx != nullptr;
  3218. src1_uma = d_Qy != nullptr;
  3219. }
  3220. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3221. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3222. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  3223. const bool qx_needs_dequant = x_non_contig;
  3224. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  3225. // Not implemented
  3226. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3227. const uint64_t x_ne = ne01 * ne00;
  3228. const uint64_t y_ne = ne11 * ne10;
  3229. const uint64_t d_ne = ne11 * ne01;
  3230. 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);
  3231. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3232. 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;
  3233. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3234. const uint64_t d_sz = sizeof(float) * d_ne;
  3235. vk_pipeline to_fp16_vk_0 = nullptr;
  3236. vk_pipeline to_fp16_vk_1 = nullptr;
  3237. if (x_non_contig) {
  3238. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  3239. }
  3240. if (y_non_contig) {
  3241. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  3242. } else {
  3243. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3244. }
  3245. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type);
  3246. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3247. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3248. GGML_ASSERT(dmmv != nullptr);
  3249. if (dryrun) {
  3250. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3251. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3252. if (
  3253. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3254. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3255. GGML_ABORT("Requested preallocation size is too large");
  3256. }
  3257. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3258. ctx->prealloc_size_x = x_sz_upd;
  3259. }
  3260. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3261. ctx->prealloc_size_y = y_sz_upd;
  3262. }
  3263. // Request descriptor sets
  3264. if (qx_needs_dequant) {
  3265. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3266. }
  3267. if (qy_needs_dequant) {
  3268. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3269. }
  3270. ggml_pipeline_request_descriptor_sets(ctx->device, dmmv, 1);
  3271. return;
  3272. }
  3273. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3274. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3275. GGML_ASSERT(d_D != nullptr);
  3276. vk_buffer d_X;
  3277. uint64_t x_buf_offset = 0;
  3278. vk_buffer d_Y;
  3279. uint64_t y_buf_offset = 0;
  3280. if(!src0_uma) {
  3281. d_Qx = src0_buf_ctx->dev_buffer;
  3282. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3283. GGML_ASSERT(d_Qx != nullptr);
  3284. }
  3285. if(!src1_uma) {
  3286. d_Qy = src1_buf_ctx->dev_buffer;
  3287. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3288. GGML_ASSERT(d_Qy != nullptr);
  3289. }
  3290. if (qx_needs_dequant) {
  3291. d_X = ctx->prealloc_x;
  3292. } else {
  3293. d_X = d_Qx;
  3294. x_buf_offset = qx_buf_offset;
  3295. GGML_ASSERT(qx_sz == x_sz);
  3296. }
  3297. if (qy_needs_dequant) {
  3298. d_Y = ctx->prealloc_y;
  3299. } else {
  3300. d_Y = d_Qy;
  3301. y_buf_offset = qy_buf_offset;
  3302. GGML_ASSERT(qy_sz == y_sz);
  3303. }
  3304. if (x_non_contig) {
  3305. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  3306. 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 });
  3307. }
  3308. if (y_non_contig) {
  3309. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  3310. 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 });
  3311. }
  3312. uint32_t stride_batch_x = ne00*ne01;
  3313. uint32_t stride_batch_y = ne10*ne11;
  3314. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3315. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3316. }
  3317. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3318. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3319. }
  3320. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  3321. uint32_t groups_x = ne01;
  3322. uint32_t groups_z = 1;
  3323. if (ne01 > max_groups_x) {
  3324. groups_z = 64;
  3325. groups_x = CEIL_DIV(groups_x, groups_z);
  3326. }
  3327. // compute
  3328. const vk_mat_vec_push_constants pc = {
  3329. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  3330. stride_batch_x, stride_batch_y, (uint32_t)(ne20*ne21),
  3331. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  3332. };
  3333. ggml_vk_sync_buffers(subctx);
  3334. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  3335. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 }, vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23} },
  3336. sizeof(vk_mat_vec_push_constants), &pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  3337. }
  3338. 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, bool dryrun = false) {
  3339. VK_LOG_DEBUG("ggml_vk_mul_mat_p021_f16_f32(" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3340. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3341. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3342. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3343. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  3344. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  3345. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  3346. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  3347. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  3348. const uint64_t ne00 = src0->ne[0];
  3349. const uint64_t ne01 = src0->ne[1];
  3350. const uint64_t ne02 = src0->ne[2];
  3351. // const uint64_t ne03 = src0->ne[3];
  3352. const uint64_t ne10 = src1->ne[0];
  3353. const uint64_t ne11 = src1->ne[1];
  3354. const uint64_t ne12 = src1->ne[2];
  3355. // const uint64_t ne13 = src1->ne[3];
  3356. GGML_ASSERT(ne11 == 1);
  3357. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3358. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3359. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3360. vk_buffer d_Qy;
  3361. size_t qy_buf_offset = 0;
  3362. bool src1_uma = false;
  3363. if (ctx->device->uma) {
  3364. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3365. src1_uma = d_Qy != nullptr;
  3366. }
  3367. const uint64_t x_ne = ne00 * ne01 * ne02;
  3368. const uint64_t y_ne = ne10 * ne11 * ne12;
  3369. const uint64_t d_ne = ne01 * ne11 * ne12;
  3370. 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);
  3371. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3372. const uint64_t d_sz = sizeof(float) * d_ne;
  3373. if (dryrun) {
  3374. // Request descriptor sets
  3375. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, 1);
  3376. return;
  3377. }
  3378. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3379. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3380. GGML_ASSERT(d_D != nullptr);
  3381. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  3382. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3383. GGML_ASSERT(d_Qx != nullptr);
  3384. if (!src1_uma) {
  3385. d_Qy = src1_buf_ctx->dev_buffer;
  3386. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3387. GGML_ASSERT(d_Qx != nullptr);
  3388. }
  3389. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3390. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  3391. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3392. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  3393. // compute
  3394. 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)) };
  3395. ggml_vk_sync_buffers(subctx);
  3396. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, 6 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  3397. }
  3398. 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, bool dryrun = false) {
  3399. VK_LOG_DEBUG("ggml_vk_mul_mat_nc_f16_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3400. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3401. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3402. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3403. GGML_ASSERT(!ggml_is_transposed(src0));
  3404. GGML_ASSERT(!ggml_is_transposed(src1));
  3405. GGML_ASSERT(!ggml_is_permuted(src0));
  3406. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  3407. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  3408. const uint64_t ne00 = src0->ne[0];
  3409. const uint64_t ne01 = src0->ne[1];
  3410. const uint64_t ne02 = src0->ne[2];
  3411. // const uint64_t ne03 = src0->ne[3];
  3412. const uint64_t nb01 = src0->nb[1];
  3413. const uint64_t nb02 = src0->nb[2];
  3414. // const uint64_t ne10 = src1->ne[0];
  3415. const uint64_t ne11 = src1->ne[1];
  3416. const uint64_t ne12 = src1->ne[2];
  3417. // const uint64_t ne13 = src1->ne[3];
  3418. GGML_ASSERT(ne11 == 1);
  3419. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3420. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3421. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3422. vk_buffer d_Qy = nullptr;
  3423. size_t qy_buf_offset = 0;
  3424. bool src1_uma = false;
  3425. if (ctx->device->uma) {
  3426. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3427. src1_uma = d_Qy != nullptr;
  3428. }
  3429. const uint64_t d_ne = ne01 * ne11 * ne12;
  3430. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  3431. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  3432. const uint64_t qx_sz = ggml_nbytes(src0);
  3433. const uint64_t qy_sz = ggml_nbytes(src1);
  3434. const uint64_t d_sz = sizeof(float) * d_ne;
  3435. if (dryrun) {
  3436. // Request descriptor sets
  3437. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  3438. return;
  3439. }
  3440. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3441. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3442. GGML_ASSERT(d_D != nullptr);
  3443. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  3444. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3445. GGML_ASSERT(d_Qx != nullptr);
  3446. if (!src1_uma) {
  3447. d_Qy = src1_buf_ctx->dev_buffer;
  3448. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3449. GGML_ASSERT(d_Qx != nullptr);
  3450. }
  3451. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3452. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  3453. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3454. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  3455. // compute
  3456. 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)) };
  3457. ggml_vk_sync_buffers(subctx);
  3458. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  3459. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, 7 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  3460. }
  3461. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3462. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  3463. if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  3464. // detect 0213 permutation, and batch size of 1
  3465. src0->nb[0] <= src0->nb[2] &&
  3466. src0->nb[2] <= src0->nb[1] &&
  3467. src0->nb[1] <= src0->nb[3] &&
  3468. src1->nb[0] <= src1->nb[2] &&
  3469. src1->nb[2] <= src1->nb[1] &&
  3470. src1->nb[1] <= src1->nb[3] &&
  3471. src0->ne[3] == 1 &&
  3472. src1->ne[3] == 1) {
  3473. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  3474. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  3475. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  3476. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  3477. } else if (dst->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  3478. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  3479. } else {
  3480. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  3481. }
  3482. }
  3483. static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, bool dryrun = false) {
  3484. VK_LOG_DEBUG("ggml_vk_mul_mat_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3485. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3486. std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3];
  3487. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3] << "),)");
  3488. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3489. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  3490. const uint64_t ne00 = src0->ne[0];
  3491. const uint64_t ne01 = src0->ne[1];
  3492. const uint64_t ne02 = src0->ne[2];
  3493. const uint64_t ne03 = src0->ne[3];
  3494. const uint64_t ne10 = src1->ne[0];
  3495. const uint64_t ne11 = src1->ne[1];
  3496. const uint64_t ne12 = src1->ne[2];
  3497. const uint64_t ne13 = src1->ne[3];
  3498. const uint64_t nei0 = ids->ne[0];
  3499. const uint64_t nei1 = ids->ne[1];
  3500. GGML_ASSERT(nei0 * nei1 <= 3072);
  3501. const uint32_t nbi1 = ids->nb[1];
  3502. const uint32_t nbi2 = ids->nb[2];
  3503. const uint64_t ne20 = dst->ne[0];
  3504. const uint64_t ne21 = dst->ne[1];
  3505. const uint64_t ne22 = dst->ne[2];
  3506. const uint64_t ne23 = dst->ne[3];
  3507. const uint64_t n_as = ne02;
  3508. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3509. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3510. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3511. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  3512. vk_buffer d_Qx;
  3513. size_t qx_buf_offset = 0;
  3514. vk_buffer d_Qy;
  3515. size_t qy_buf_offset = 0;
  3516. vk_buffer d_ids;
  3517. size_t ids_buf_offset = 0;
  3518. bool src0_uma = false;
  3519. bool src1_uma = false;
  3520. bool ids_uma = false;
  3521. if (ctx->device->uma) {
  3522. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3523. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3524. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  3525. src0_uma = d_Qx != nullptr;
  3526. src1_uma = d_Qy != nullptr;
  3527. ids_uma = d_ids != nullptr;
  3528. }
  3529. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3530. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3531. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  3532. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type, (ggml_prec)dst->op_params[0]);
  3533. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  3534. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  3535. if (qx_needs_dequant) {
  3536. GGML_ABORT("fatal error");
  3537. }
  3538. // Not implemented
  3539. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3540. const uint64_t x_ne = ne01 * ne00;
  3541. const uint64_t y_ne = ne11 * ne10;
  3542. const uint64_t d_ne = ne21 * ne20;
  3543. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1));
  3544. const bool aligned = ne10 == kpad && ne01 > 8 && nei1 > 8;
  3545. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned);
  3546. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  3547. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3548. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  3549. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3550. const uint64_t ids_sz = nbi2;
  3551. const uint64_t d_sz = sizeof(float) * d_ne;
  3552. vk_pipeline to_fp16_vk_0 = nullptr;
  3553. vk_pipeline to_fp16_vk_1 = nullptr;
  3554. if (x_non_contig) {
  3555. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, GGML_TYPE_F16);
  3556. } else {
  3557. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  3558. }
  3559. if (y_non_contig) {
  3560. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, GGML_TYPE_F16);
  3561. } else {
  3562. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3563. }
  3564. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3565. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3566. if (dryrun) {
  3567. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3568. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3569. if (
  3570. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3571. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3572. GGML_ABORT("Requested preallocation size is too large");
  3573. }
  3574. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3575. ctx->prealloc_size_x = x_sz_upd;
  3576. }
  3577. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3578. ctx->prealloc_size_y = y_sz_upd;
  3579. }
  3580. // Request descriptor sets
  3581. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3582. if (qx_needs_dequant) {
  3583. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3584. }
  3585. if (qy_needs_dequant) {
  3586. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3587. }
  3588. return;
  3589. }
  3590. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3591. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3592. GGML_ASSERT(d_D != nullptr);
  3593. vk_buffer d_X;
  3594. uint64_t x_buf_offset = 0;
  3595. vk_buffer d_Y;
  3596. uint64_t y_buf_offset = 0;
  3597. if (!src0_uma) {
  3598. d_Qx = src0_buf_ctx->dev_buffer;
  3599. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3600. GGML_ASSERT(d_Qx != nullptr);
  3601. }
  3602. if (!src1_uma) {
  3603. d_Qy = src1_buf_ctx->dev_buffer;
  3604. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3605. GGML_ASSERT(d_Qy != nullptr);
  3606. }
  3607. if (!ids_uma) {
  3608. d_ids = ids_buf_ctx->dev_buffer;
  3609. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  3610. GGML_ASSERT(d_ids != nullptr);
  3611. }
  3612. if (qx_needs_dequant) {
  3613. d_X = ctx->prealloc_x;
  3614. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  3615. } else {
  3616. d_X = d_Qx;
  3617. x_buf_offset = qx_buf_offset;
  3618. GGML_ASSERT(qx_sz == x_sz);
  3619. }
  3620. if (qy_needs_dequant) {
  3621. d_Y = ctx->prealloc_y;
  3622. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  3623. } else {
  3624. d_Y = d_Qy;
  3625. y_buf_offset = qy_buf_offset;
  3626. GGML_ASSERT(qy_sz == y_sz);
  3627. }
  3628. if (x_non_contig) {
  3629. 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 });
  3630. } else if (qx_needs_dequant) {
  3631. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  3632. ggml_vk_sync_buffers(subctx);
  3633. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  3634. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  3635. }
  3636. if (y_non_contig) {
  3637. 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 });
  3638. }
  3639. uint32_t stride_batch_x = ne00*ne01;
  3640. uint32_t stride_batch_y = ne10*ne11;
  3641. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3642. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3643. }
  3644. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3645. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3646. }
  3647. // compute
  3648. ggml_vk_matmul_id(
  3649. ctx, subctx, pipeline,
  3650. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  3651. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  3652. ne01, ne21, ne10, ne10, ne10, ne01,
  3653. stride_batch_x, stride_batch_y, ne20*ne21,
  3654. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11
  3655. ); // NOLINT
  3656. }
  3657. static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, bool dryrun = false) {
  3658. VK_LOG_DEBUG("ggml_vk_mul_mat_vec_id_q_f16((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  3659. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  3660. std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3];
  3661. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3662. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3663. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3664. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3665. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  3666. const uint64_t ne00 = src0->ne[0];
  3667. const uint64_t ne01 = src0->ne[1];
  3668. const uint64_t ne02 = src0->ne[2];
  3669. const uint64_t ne03 = src0->ne[3];
  3670. const uint64_t ne10 = src1->ne[0];
  3671. const uint64_t ne11 = src1->ne[1];
  3672. const uint64_t ne12 = src1->ne[2];
  3673. const uint64_t ne13 = src1->ne[3];
  3674. const uint64_t nei0 = ids->ne[0];
  3675. const uint64_t nei1 = ids->ne[1];
  3676. const uint64_t nbi2 = ids->nb[2];
  3677. GGML_ASSERT(nei1 == 1);
  3678. const uint64_t ne20 = dst->ne[0];
  3679. const uint64_t ne21 = dst->ne[1];
  3680. const uint64_t ne22 = dst->ne[2];
  3681. const uint64_t ne23 = dst->ne[3];
  3682. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3683. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3684. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3685. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  3686. vk_buffer d_Qx;
  3687. size_t qx_buf_offset = 0;
  3688. vk_buffer d_Qy;
  3689. size_t qy_buf_offset = 0;
  3690. vk_buffer d_ids;
  3691. size_t ids_buf_offset = 0;
  3692. bool src0_uma = false;
  3693. bool src1_uma = false;
  3694. bool ids_uma = false;
  3695. if (ctx->device->uma) {
  3696. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3697. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3698. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  3699. src0_uma = d_Qx != nullptr;
  3700. src1_uma = d_Qy != nullptr;
  3701. ids_uma = d_ids != nullptr;
  3702. }
  3703. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3704. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3705. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  3706. const bool qx_needs_dequant = x_non_contig;
  3707. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  3708. // Not implemented
  3709. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3710. const uint64_t x_ne = ne01 * ne00;
  3711. const uint64_t y_ne = ne11 * ne10;
  3712. const uint64_t d_ne = ne21 * ne20;
  3713. 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);
  3714. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3715. 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;
  3716. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3717. const uint64_t ids_sz = nbi2;
  3718. const uint64_t d_sz = sizeof(float) * d_ne;
  3719. vk_pipeline to_fp16_vk_0 = nullptr;
  3720. vk_pipeline to_fp16_vk_1 = nullptr;
  3721. if (x_non_contig) {
  3722. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  3723. }
  3724. if (y_non_contig) {
  3725. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  3726. } else {
  3727. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3728. }
  3729. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  3730. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3731. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3732. GGML_ASSERT(dmmv != nullptr);
  3733. if (dryrun) {
  3734. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3735. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3736. if (
  3737. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3738. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3739. GGML_ABORT("Requested preallocation size is too large");
  3740. }
  3741. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3742. ctx->prealloc_size_x = x_sz_upd;
  3743. }
  3744. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3745. ctx->prealloc_size_y = y_sz_upd;
  3746. }
  3747. // Request descriptor sets
  3748. if (qx_needs_dequant) {
  3749. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3750. }
  3751. if (qy_needs_dequant) {
  3752. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3753. }
  3754. ggml_pipeline_request_descriptor_sets(ctx->device, dmmv, 1);
  3755. return;
  3756. }
  3757. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3758. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3759. GGML_ASSERT(d_D != nullptr);
  3760. vk_buffer d_X;
  3761. uint64_t x_buf_offset = 0;
  3762. vk_buffer d_Y;
  3763. uint64_t y_buf_offset = 0;
  3764. if(!src0_uma) {
  3765. d_Qx = src0_buf_ctx->dev_buffer;
  3766. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3767. GGML_ASSERT(d_Qx != nullptr);
  3768. }
  3769. if(!src1_uma) {
  3770. d_Qy = src1_buf_ctx->dev_buffer;
  3771. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3772. GGML_ASSERT(d_Qy != nullptr);
  3773. }
  3774. if(!ids_uma) {
  3775. d_ids = ids_buf_ctx->dev_buffer;
  3776. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  3777. GGML_ASSERT(d_ids != nullptr);
  3778. }
  3779. if (qx_needs_dequant) {
  3780. d_X = ctx->prealloc_x;
  3781. } else {
  3782. d_X = d_Qx;
  3783. x_buf_offset = qx_buf_offset;
  3784. GGML_ASSERT(qx_sz == x_sz);
  3785. }
  3786. if (qy_needs_dequant) {
  3787. d_Y = ctx->prealloc_y;
  3788. } else {
  3789. d_Y = d_Qy;
  3790. y_buf_offset = qy_buf_offset;
  3791. GGML_ASSERT(qy_sz == y_sz);
  3792. }
  3793. if (x_non_contig) {
  3794. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  3795. 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 });
  3796. }
  3797. if (y_non_contig) {
  3798. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  3799. 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 });
  3800. }
  3801. uint32_t stride_batch_y = ne10*ne11;
  3802. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3803. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3804. }
  3805. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  3806. uint32_t groups_x = ne01;
  3807. uint32_t groups_z = 1;
  3808. if (ne01 > max_groups_x) {
  3809. groups_z = 64;
  3810. groups_x = CEIL_DIV(groups_x, groups_z);
  3811. }
  3812. // compute
  3813. const vk_mat_vec_id_push_constants pc = {
  3814. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  3815. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  3816. (uint32_t)nei0, (uint32_t)ne11,
  3817. };
  3818. ggml_vk_sync_buffers(subctx);
  3819. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  3820. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  3821. vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23}, vk_subbuffer{ d_ids, ids_buf_offset, ids_sz } },
  3822. sizeof(vk_mat_vec_id_push_constants), &pc, { groups_x, (uint32_t)nei0, groups_z });
  3823. }
  3824. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  3825. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  3826. if (src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  3827. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  3828. } else {
  3829. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  3830. }
  3831. }
  3832. static void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v, const ggml_tensor * mask, ggml_tensor * dst, bool dryrun = false) {
  3833. VK_LOG_DEBUG("ggml_vk_flash_attn((" << q << ", name=" << q->name << ", type=" << q->type << ", ne0=" << q->ne[0] << ", ne1=" << q->ne[1] << ", ne2=" << q->ne[2] << ", ne3=" << q->ne[3] << ", nb0=" << q->nb[0] << ", nb1=" << q->nb[1] << ", nb2=" << q->nb[2] << ", nb3=" << q->nb[3];
  3834. std::cerr << "), (" << k << ", name=" << k->name << ", type=" << k->type << ", ne0=" << k->ne[0] << ", ne1=" << k->ne[1] << ", ne2=" << k->ne[2] << ", ne3=" << k->ne[3] << ", nb0=" << k->nb[0] << ", nb1=" << k->nb[1] << ", nb2=" << k->nb[2] << ", nb3=" << k->nb[3];
  3835. std::cerr << "), (" << v << ", name=" << v->name << ", type=" << v->type << ", ne0=" << v->ne[0] << ", ne1=" << v->ne[1] << ", ne2=" << v->ne[2] << ", ne3=" << v->ne[3] << ", nb0=" << v->nb[0] << ", nb1=" << v->nb[1] << ", nb2=" << v->nb[2] << ", nb3=" << v->nb[3];
  3836. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  3837. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3838. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  3839. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  3840. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  3841. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  3842. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  3843. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  3844. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  3845. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  3846. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  3847. const uint32_t nbm1 = mask ? mask->nb[1] : 0;
  3848. const uint32_t D = neq0;
  3849. const uint32_t N = neq1;
  3850. const uint32_t KV = nek1;
  3851. GGML_ASSERT(ne0 == D);
  3852. GGML_ASSERT(ne2 == N);
  3853. // input tensor rows must be contiguous
  3854. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  3855. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  3856. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  3857. GGML_ASSERT(neq0 == D);
  3858. GGML_ASSERT(nek0 == D);
  3859. GGML_ASSERT(nev0 == D);
  3860. GGML_ASSERT(neq1 == N);
  3861. GGML_ASSERT(nev0 == D);
  3862. GGML_ASSERT(nev1 == nek1);
  3863. // dst cannot be transposed or permuted
  3864. GGML_ASSERT(nb0 == sizeof(float));
  3865. GGML_ASSERT(nb0 <= nb1);
  3866. GGML_ASSERT(nb1 <= nb2);
  3867. GGML_ASSERT(nb2 <= nb3);
  3868. assert(dst->type == GGML_TYPE_F32);
  3869. assert(q->type == GGML_TYPE_F32);
  3870. assert(k->type == v->type);
  3871. vk_pipeline *pipelines;
  3872. // XXX TODO other backends may be changing accumulator precision to default to f32 soon
  3873. bool f32acc = dst->op_params[3] == GGML_PREC_F32;
  3874. bool small_rows = N <= flash_attention_num_small_rows;
  3875. switch (D) {
  3876. case 64: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D64[k->type][f32acc][small_rows][0]; break;
  3877. case 80: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D80[k->type][f32acc][small_rows][0]; break;
  3878. case 96: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D96[k->type][f32acc][small_rows][0]; break;
  3879. case 112: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D112[k->type][f32acc][small_rows][0]; break;
  3880. case 128: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D128[k->type][f32acc][small_rows][0]; break;
  3881. case 256: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D256[k->type][f32acc][small_rows][0]; break;
  3882. default:
  3883. assert(!"unsupported D value");
  3884. return;
  3885. }
  3886. assert(pipelines);
  3887. bool aligned = (KV % pipelines[1]->align) == 0;
  3888. vk_pipeline pipeline = pipelines[aligned];
  3889. assert(pipeline);
  3890. if (dryrun) {
  3891. // Request descriptor sets
  3892. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3893. return;
  3894. }
  3895. float scale = 1.0f;
  3896. float max_bias = 0.0f;
  3897. float logit_softcap = 0.0f;
  3898. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  3899. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  3900. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  3901. if (logit_softcap != 0) {
  3902. scale /= logit_softcap;
  3903. }
  3904. const uint32_t n_head_kv = neq2;
  3905. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  3906. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  3907. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  3908. ggml_vk_sync_buffers(subctx);
  3909. vk_buffer d_Q, d_K, d_V, d_D, d_M;
  3910. uint64_t q_buf_offset, k_buf_offset, v_buf_offset, d_buf_offset, m_buf_offset;
  3911. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false;
  3912. if (ctx->device->uma) {
  3913. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  3914. ggml_vk_host_get(ctx->device, k->data, d_K, q_buf_offset);
  3915. ggml_vk_host_get(ctx->device, v->data, d_V, q_buf_offset);
  3916. ggml_vk_host_get(ctx->device, dst->data, d_D, q_buf_offset);
  3917. Q_uma = d_Q != nullptr;
  3918. K_uma = d_K != nullptr;
  3919. V_uma = d_V != nullptr;
  3920. D_uma = d_D != nullptr;
  3921. if (mask) {
  3922. ggml_vk_host_get(ctx->device, mask->data, d_M, q_buf_offset);
  3923. M_uma = d_M != nullptr;
  3924. }
  3925. }
  3926. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3927. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  3928. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  3929. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  3930. if (!Q_uma) {
  3931. d_Q = q_buf_ctx->dev_buffer;
  3932. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  3933. }
  3934. if (!K_uma) {
  3935. d_K = k_buf_ctx->dev_buffer;
  3936. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  3937. }
  3938. if (!V_uma) {
  3939. d_V = v_buf_ctx->dev_buffer;
  3940. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  3941. }
  3942. if (!D_uma) {
  3943. d_D = d_buf_ctx->dev_buffer;
  3944. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3945. }
  3946. if (!M_uma) {
  3947. d_M = d_Q;
  3948. m_buf_offset = q_buf_offset;
  3949. if (mask) {
  3950. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  3951. d_M = m_buf_ctx->dev_buffer;
  3952. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  3953. }
  3954. }
  3955. const vk_flash_attn_push_constants pc = { N, KV, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3, (uint32_t)neq2, (uint32_t)neq3, (uint32_t)nek2, (uint32_t)nek3, (uint32_t)nev2, (uint32_t)nev3, nem1, (uint32_t)nbq2, (uint32_t)nbq3, (uint32_t)nbk2, (uint32_t)nbk3, (uint32_t)nbv2, (uint32_t)nbv3, nbm1, scale, max_bias, logit_softcap, mask != nullptr, n_head_log2, m0, m1 };
  3956. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  3957. {
  3958. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  3959. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  3960. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  3961. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  3962. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  3963. },
  3964. sizeof(vk_flash_attn_push_constants), &pc, { (uint32_t)neq1, (uint32_t)neq2, (uint32_t)neq3 });
  3965. }
  3966. 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) {
  3967. switch (op) {
  3968. case GGML_OP_GET_ROWS:
  3969. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  3970. if (dst->type == GGML_TYPE_F16) {
  3971. return ctx->device->pipeline_get_rows[src0->type];
  3972. }
  3973. if (dst->type == GGML_TYPE_F32) {
  3974. return ctx->device->pipeline_get_rows_f32[src0->type];
  3975. }
  3976. return nullptr;
  3977. case GGML_OP_ACC:
  3978. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  3979. return ctx->device->pipeline_acc_f32;
  3980. }
  3981. return nullptr;
  3982. case GGML_OP_ADD:
  3983. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  3984. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_f32_norepeat : ctx->device->pipeline_add_f32;
  3985. }
  3986. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  3987. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_f16_f32_f16_norepeat : ctx->device->pipeline_add_f16_f32_f16;
  3988. }
  3989. return nullptr;
  3990. case GGML_OP_MUL:
  3991. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  3992. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_f32_norepeat : ctx->device->pipeline_mul_f32;
  3993. }
  3994. return nullptr;
  3995. case GGML_OP_DIV:
  3996. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  3997. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_f32_norepeat : ctx->device->pipeline_div_f32;
  3998. }
  3999. return nullptr;
  4000. case GGML_OP_CONCAT:
  4001. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4002. return ctx->device->pipeline_concat_f32;
  4003. }
  4004. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4005. return ctx->device->pipeline_concat_f16;
  4006. }
  4007. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  4008. return ctx->device->pipeline_concat_i32;
  4009. }
  4010. return nullptr;
  4011. case GGML_OP_UPSCALE:
  4012. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4013. return ctx->device->pipeline_upscale_f32;
  4014. }
  4015. return nullptr;
  4016. case GGML_OP_SCALE:
  4017. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4018. return ctx->device->pipeline_scale_f32;
  4019. }
  4020. return nullptr;
  4021. case GGML_OP_SQR:
  4022. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4023. return ctx->device->pipeline_sqr_f32;
  4024. }
  4025. return nullptr;
  4026. case GGML_OP_SIN:
  4027. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4028. return ctx->device->pipeline_sin_f32;
  4029. }
  4030. return nullptr;
  4031. case GGML_OP_COS:
  4032. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4033. return ctx->device->pipeline_cos_f32;
  4034. }
  4035. return nullptr;
  4036. case GGML_OP_CLAMP:
  4037. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4038. return ctx->device->pipeline_clamp_f32;
  4039. }
  4040. return nullptr;
  4041. case GGML_OP_PAD:
  4042. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4043. return ctx->device->pipeline_pad_f32;
  4044. }
  4045. return nullptr;
  4046. case GGML_OP_REPEAT:
  4047. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  4048. return ctx->device->pipeline_repeat_f32;
  4049. }
  4050. return nullptr;
  4051. case GGML_OP_CPY:
  4052. case GGML_OP_CONT:
  4053. case GGML_OP_DUP:
  4054. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  4055. case GGML_OP_NORM:
  4056. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4057. return ctx->device->pipeline_norm_f32;
  4058. }
  4059. return nullptr;
  4060. case GGML_OP_GROUP_NORM:
  4061. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4062. return ctx->device->pipeline_group_norm_f32;
  4063. }
  4064. return nullptr;
  4065. case GGML_OP_RMS_NORM:
  4066. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4067. return ctx->device->pipeline_rms_norm_f32;
  4068. }
  4069. return nullptr;
  4070. case GGML_OP_UNARY:
  4071. switch (ggml_get_unary_op(dst)) {
  4072. case GGML_UNARY_OP_SILU:
  4073. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4074. return ctx->device->pipeline_silu_f32;
  4075. }
  4076. break;
  4077. case GGML_UNARY_OP_GELU:
  4078. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4079. return ctx->device->pipeline_gelu_f32;
  4080. }
  4081. break;
  4082. case GGML_UNARY_OP_GELU_QUICK:
  4083. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4084. return ctx->device->pipeline_gelu_quick_f32;
  4085. }
  4086. break;
  4087. case GGML_UNARY_OP_RELU:
  4088. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4089. return ctx->device->pipeline_relu_f32;
  4090. }
  4091. break;
  4092. case GGML_UNARY_OP_TANH:
  4093. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4094. return ctx->device->pipeline_tanh_f32;
  4095. }
  4096. break;
  4097. default:
  4098. break;
  4099. }
  4100. return nullptr;
  4101. case GGML_OP_DIAG_MASK_INF:
  4102. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4103. return ctx->device->pipeline_diag_mask_inf_f32;
  4104. }
  4105. return nullptr;
  4106. case GGML_OP_SOFT_MAX:
  4107. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  4108. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  4109. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  4110. }
  4111. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  4112. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  4113. }
  4114. return nullptr;
  4115. case GGML_OP_ROPE:
  4116. {
  4117. const int mode = ((const int32_t *) dst->op_params)[2];
  4118. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  4119. if (is_neox) {
  4120. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4121. return ctx->device->pipeline_rope_neox_f32;
  4122. }
  4123. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4124. return ctx->device->pipeline_rope_neox_f16;
  4125. }
  4126. } else {
  4127. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4128. return ctx->device->pipeline_rope_norm_f32;
  4129. }
  4130. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4131. return ctx->device->pipeline_rope_norm_f16;
  4132. }
  4133. }
  4134. return nullptr;
  4135. }
  4136. case GGML_OP_ARGSORT:
  4137. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  4138. return ctx->device->pipeline_argsort_f32;
  4139. }
  4140. return nullptr;
  4141. case GGML_OP_SUM_ROWS:
  4142. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4143. return ctx->device->pipeline_sum_rows_f32;
  4144. }
  4145. return nullptr;
  4146. case GGML_OP_IM2COL:
  4147. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4148. return ctx->device->pipeline_im2col_f32;
  4149. }
  4150. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  4151. return ctx->device->pipeline_im2col_f32_f16;
  4152. }
  4153. return nullptr;
  4154. case GGML_OP_TIMESTEP_EMBEDDING:
  4155. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4156. return ctx->device->pipeline_timestep_embedding_f32;
  4157. }
  4158. return nullptr;
  4159. case GGML_OP_POOL_2D:
  4160. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4161. return ctx->device->pipeline_pool2d_f32;
  4162. }
  4163. return nullptr;
  4164. case GGML_OP_LEAKY_RELU:
  4165. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4166. return ctx->device->pipeline_leaky_relu_f32;
  4167. }
  4168. return nullptr;
  4169. default:
  4170. return nullptr;
  4171. }
  4172. GGML_UNUSED(src2);
  4173. }
  4174. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  4175. switch (op) {
  4176. case GGML_OP_CPY:
  4177. case GGML_OP_GET_ROWS:
  4178. case GGML_OP_ADD:
  4179. case GGML_OP_MUL:
  4180. case GGML_OP_DIV:
  4181. case GGML_OP_CONCAT:
  4182. case GGML_OP_UPSCALE:
  4183. case GGML_OP_SQR:
  4184. case GGML_OP_SIN:
  4185. case GGML_OP_COS:
  4186. case GGML_OP_CLAMP:
  4187. case GGML_OP_PAD:
  4188. case GGML_OP_REPEAT:
  4189. return true;
  4190. default:
  4191. return false;
  4192. }
  4193. }
  4194. template<typename PC>
  4195. 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, PC&& pc, bool dryrun = false) {
  4196. VK_LOG_DEBUG("ggml_vk_op_f32((" << src0 << ", name=" << src0->name << ", type=" << src0->type << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  4197. if (src1 != nullptr) {
  4198. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  4199. }
  4200. if (src2 != nullptr) {
  4201. std::cerr << "), (" << src2 << ", name=" << src2->name << ", type=" << src2->type << ", ne0=" << src2->ne[0] << ", ne1=" << src2->ne[1] << ", ne2=" << src2->ne[2] << ", ne3=" << src2->ne[3] << ", nb0=" << src2->nb[0] << ", nb1=" << src2->nb[1] << ", nb2=" << src2->nb[2] << ", nb3=" << src2->nb[3];
  4202. }
  4203. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  4204. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  4205. GGML_ASSERT(op == GGML_OP_GET_ROWS || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  4206. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  4207. GGML_ASSERT(dst->buffer != nullptr);
  4208. const uint64_t ne00 = src0->ne[0];
  4209. const uint64_t ne01 = src0->ne[1];
  4210. const uint64_t ne02 = src0->ne[2];
  4211. const uint64_t ne03 = src0->ne[3];
  4212. const uint64_t ne0 = ne00 * ne01;
  4213. const bool use_src1 = src1 != nullptr;
  4214. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  4215. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  4216. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  4217. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  4218. const uint64_t ne1 = ne10 * ne11;
  4219. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  4220. const bool use_src2 = src2 != nullptr;
  4221. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  4222. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  4223. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  4224. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  4225. const uint64_t ne2 = ne20 * ne21;
  4226. const uint64_t ned0 = dst->ne[0];
  4227. const uint64_t ned1 = dst->ne[1];
  4228. const uint64_t ned2 = dst->ne[2];
  4229. const uint64_t ned3 = dst->ne[3];
  4230. const uint64_t ned = ned0 * ned1;
  4231. init_pushconst_fastdiv(pc);
  4232. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  4233. if (pipeline == nullptr) {
  4234. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  4235. if (src1 != nullptr) {
  4236. std::cerr << " and " << ggml_type_name(src1->type);
  4237. }
  4238. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  4239. GGML_ABORT("fatal error");
  4240. }
  4241. if (dryrun) {
  4242. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  4243. return;
  4244. }
  4245. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  4246. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4247. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  4248. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  4249. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  4250. vk_buffer d_X = nullptr;
  4251. size_t x_buf_offset = 0;
  4252. vk_buffer d_Y = nullptr;
  4253. size_t y_buf_offset = 0;
  4254. vk_buffer d_Z = nullptr;
  4255. size_t z_buf_offset = 0;
  4256. bool src0_uma = false;
  4257. bool src1_uma = false;
  4258. bool src2_uma = false;
  4259. if (ctx->device->uma) {
  4260. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  4261. src0_uma = d_X != nullptr;
  4262. if (use_src1) {
  4263. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  4264. src1_uma = d_Y != nullptr;
  4265. }
  4266. if (use_src2) {
  4267. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  4268. src2_uma = d_Z != nullptr;
  4269. }
  4270. }
  4271. uint64_t x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0;
  4272. uint64_t y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 : 0;
  4273. uint64_t z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 : 0;
  4274. uint64_t d_sz = ggml_type_size(dst->type) * ned;
  4275. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  4276. // Workaround for tiny tensor inputs on ROPE
  4277. if (op == GGML_OP_ROPE && use_src1 && y_sz > d_D->size) {
  4278. y_sz = VK_WHOLE_SIZE;
  4279. }
  4280. GGML_ASSERT(d_D != nullptr);
  4281. uint64_t d_buf_offset = ((vk_tensor_offset(dst) + dst->view_offs) / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  4282. GGML_ASSERT(d_buf_offset == vk_tensor_offset(dst) || op == GGML_OP_CPY); // NOLINT
  4283. if(!src0_uma) {
  4284. d_X = src0_buf_ctx->dev_buffer;
  4285. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  4286. GGML_ASSERT(d_X != nullptr);
  4287. }
  4288. if (use_src1 && !src1_uma) {
  4289. d_Y = src1_buf_ctx->dev_buffer;
  4290. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  4291. GGML_ASSERT(d_Y != nullptr);
  4292. }
  4293. if (use_src2 && !src2_uma) {
  4294. d_Z = src2_buf_ctx->dev_buffer;
  4295. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  4296. GGML_ASSERT(d_Z != nullptr);
  4297. }
  4298. if (op_supports_incontiguous) {
  4299. x_sz = ggml_nbytes(src0);
  4300. y_sz = use_src1 ? ggml_nbytes(src1) : 0;
  4301. z_sz = use_src2 ? ggml_nbytes(src2) : 0;
  4302. d_sz = ggml_nbytes(dst);
  4303. if (x_buf_offset + x_sz >= d_X->size) {
  4304. x_sz = VK_WHOLE_SIZE;
  4305. }
  4306. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  4307. y_sz = VK_WHOLE_SIZE;
  4308. }
  4309. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  4310. z_sz = VK_WHOLE_SIZE;
  4311. }
  4312. if (d_buf_offset + d_sz >= d_D->size) {
  4313. d_sz = VK_WHOLE_SIZE;
  4314. }
  4315. }
  4316. std::array<uint32_t, 3> elements;
  4317. // Single call if dimension 2 is contiguous
  4318. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  4319. switch (op) {
  4320. case GGML_OP_NORM:
  4321. case GGML_OP_RMS_NORM:
  4322. case GGML_OP_SOFT_MAX:
  4323. case GGML_OP_SUM_ROWS:
  4324. {
  4325. const uint32_t nr = ggml_nrows(src0);
  4326. if (nr > 262144) {
  4327. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  4328. } else if (nr > 512) {
  4329. elements = { 512, CEIL_DIV(nr, 512), 1 };
  4330. } else {
  4331. elements = { nr, 1, 1 };
  4332. }
  4333. } break;
  4334. case GGML_OP_GROUP_NORM:
  4335. {
  4336. const uint32_t num_groups = dst->op_params[0];
  4337. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  4338. } break;
  4339. case GGML_OP_DIAG_MASK_INF:
  4340. case GGML_OP_ROPE:
  4341. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  4342. break;
  4343. case GGML_OP_GET_ROWS:
  4344. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  4345. break;
  4346. case GGML_OP_ARGSORT:
  4347. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  4348. break;
  4349. case GGML_OP_IM2COL:
  4350. {
  4351. const bool is_2D = dst->op_params[6] == 1;
  4352. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  4353. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  4354. const uint32_t KW = src0->ne[0];
  4355. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  4356. const uint32_t OW = dst->ne[1];
  4357. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  4358. elements = { OW * KW * KH, OH, batch * IC };
  4359. } break;
  4360. case GGML_OP_TIMESTEP_EMBEDDING:
  4361. {
  4362. const uint32_t dim = dst->op_params[0];
  4363. uint32_t half_ceil = (dim + 1) / 2;
  4364. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  4365. } break;
  4366. case GGML_OP_POOL_2D:
  4367. {
  4368. const uint32_t N = dst->ne[3];
  4369. const uint32_t OC = dst->ne[2];
  4370. const uint32_t OH = dst->ne[1];
  4371. const uint32_t OW = dst->ne[0];
  4372. elements = { N * OC * OH * OW, 1, 1};
  4373. } break;
  4374. case GGML_OP_ADD:
  4375. case GGML_OP_DIV:
  4376. case GGML_OP_MUL:
  4377. case GGML_OP_SCALE:
  4378. case GGML_OP_SQR:
  4379. case GGML_OP_SIN:
  4380. case GGML_OP_COS:
  4381. case GGML_OP_CLAMP:
  4382. case GGML_OP_PAD:
  4383. case GGML_OP_REPEAT:
  4384. case GGML_OP_CPY:
  4385. case GGML_OP_CONCAT:
  4386. case GGML_OP_UPSCALE:
  4387. case GGML_OP_UNARY:
  4388. {
  4389. const uint32_t ne = ggml_nelements(dst);
  4390. if (ne > 262144) {
  4391. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  4392. } else if (ne > 512) {
  4393. elements = { 512, CEIL_DIV(ne, 512), 1 };
  4394. } else {
  4395. elements = { ne, 1, 1 };
  4396. }
  4397. } break;
  4398. default:
  4399. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  4400. break;
  4401. }
  4402. if (!op_supports_incontiguous) {
  4403. if (x_sz != VK_WHOLE_SIZE) {
  4404. x_sz *= ne02 * ne03;
  4405. }
  4406. if (use_src1 && y_sz != VK_WHOLE_SIZE) {
  4407. y_sz *= ne12 * ne13;
  4408. }
  4409. if (use_src2 && z_sz != VK_WHOLE_SIZE) {
  4410. z_sz *= ne22 * ne23;
  4411. }
  4412. if (d_sz != VK_WHOLE_SIZE) {
  4413. d_sz *= ned2 * ned3;
  4414. }
  4415. }
  4416. if (op == GGML_OP_SOFT_MAX) {
  4417. // Empty src1 is possible in soft_max, but the shader needs a buffer
  4418. vk_subbuffer subbuf_y;
  4419. if (use_src1) {
  4420. subbuf_y = { d_Y, y_buf_offset, y_sz };
  4421. } else {
  4422. subbuf_y = { d_X, 0, x_sz };
  4423. }
  4424. ggml_vk_sync_buffers(subctx);
  4425. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4426. } else if (op == GGML_OP_ROPE) {
  4427. // Empty src2 is possible in rope, but the shader needs a buffer
  4428. vk_subbuffer subbuf_z;
  4429. if (use_src2) {
  4430. subbuf_z = { d_Z, z_buf_offset, z_sz };
  4431. } else {
  4432. subbuf_z = { d_X, 0, x_sz };
  4433. }
  4434. ggml_vk_sync_buffers(subctx);
  4435. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, subbuf_z, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4436. } else if (op == GGML_OP_IM2COL) {
  4437. // im2col uses only src1 and dst buffers
  4438. ggml_vk_sync_buffers(subctx);
  4439. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4440. } else if (use_src2) {
  4441. ggml_vk_sync_buffers(subctx);
  4442. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4443. } else if (use_src1) {
  4444. ggml_vk_sync_buffers(subctx);
  4445. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4446. } else {
  4447. ggml_vk_sync_buffers(subctx);
  4448. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, sizeof(PC), &pc, elements);
  4449. }
  4450. }
  4451. static void ggml_vk_get_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4452. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4453. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4454. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4455. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GET_ROWS, {
  4456. (uint32_t)ggml_nelements(src0),
  4457. (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,
  4458. (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,
  4459. (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,
  4460. 0,
  4461. 0.0f, 0.0f, 0,
  4462. }, dryrun);
  4463. }
  4464. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4465. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4466. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4467. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4468. const uint32_t d_offset = ((vk_tensor_offset(dst) + dst->view_offs) % ctx->device->properties.limits.minStorageBufferOffsetAlignment) / dst_type_size;
  4469. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  4470. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  4471. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  4472. int offset = dst->op_params[3] / 4; // offset in bytes
  4473. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ACC, {
  4474. (uint32_t)ggml_nelements(src0),
  4475. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)nb1, (uint32_t)nb2, (uint32_t)src0->nb[3] / src0_type_size,
  4476. (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,
  4477. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t)nb1, (uint32_t)nb2, (uint32_t) dst->nb[3] / dst_type_size,
  4478. d_offset,
  4479. 0.0f, 0.0f, offset,
  4480. }, dryrun);
  4481. }
  4482. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4483. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4484. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4485. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4486. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ADD, {
  4487. (uint32_t)ggml_nelements(src0),
  4488. (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,
  4489. (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,
  4490. (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,
  4491. 0,
  4492. 0.0f, 0.0f, 0,
  4493. }, dryrun);
  4494. }
  4495. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4496. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4497. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4498. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4499. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_MUL, {
  4500. (uint32_t)ggml_nelements(src0),
  4501. (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,
  4502. (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,
  4503. (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,
  4504. 0,
  4505. 0.0f, 0.0f, 0,
  4506. }, dryrun);
  4507. }
  4508. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4509. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4510. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4511. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4512. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_DIV, {
  4513. (uint32_t)ggml_nelements(src0),
  4514. (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,
  4515. (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,
  4516. (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,
  4517. 0,
  4518. 0.0f, 0.0f, 0,
  4519. }, dryrun);
  4520. }
  4521. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4522. int * op_params = (int *)dst->op_params;
  4523. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4524. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4525. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4526. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONCAT, {
  4527. (uint32_t)ggml_nelements(dst),
  4528. (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,
  4529. (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,
  4530. (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,
  4531. 0,
  4532. 0.0f, 0.0f, op_params[0],
  4533. }, dryrun);
  4534. }
  4535. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4536. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4537. const float sf0 = (float)dst->ne[0] / src0->ne[0];
  4538. const float sf1 = (float)dst->ne[1] / src0->ne[1];
  4539. const float sf2 = (float)dst->ne[2] / src0->ne[2];
  4540. const float sf3 = (float)dst->ne[3] / src0->ne[3];
  4541. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  4542. (uint32_t)ggml_nelements(dst), 0,
  4543. (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,
  4544. (uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2],(uint32_t)dst->ne[3],
  4545. sf0, sf1, sf2, sf3,
  4546. }, dryrun);
  4547. }
  4548. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4549. float * op_params = (float *)dst->op_params;
  4550. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4551. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4552. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SCALE, {
  4553. (uint32_t)ggml_nelements(src0),
  4554. (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,
  4555. (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,
  4556. 0,
  4557. op_params[0], 0.0f
  4558. }, dryrun);
  4559. }
  4560. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4561. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4562. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4563. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQR, {
  4564. (uint32_t)ggml_nelements(src0),
  4565. (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,
  4566. (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,
  4567. 0,
  4568. 0.0f, 0.0f,
  4569. }, dryrun);
  4570. }
  4571. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4572. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4573. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4574. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SIN, {
  4575. (uint32_t)ggml_nelements(src0),
  4576. (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,
  4577. (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,
  4578. 0,
  4579. 0.0f, 0.0f,
  4580. }, dryrun);
  4581. }
  4582. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4583. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4584. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4585. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_COS, {
  4586. (uint32_t)ggml_nelements(src0),
  4587. (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,
  4588. (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,
  4589. 0,
  4590. 0.0f, 0.0f,
  4591. }, dryrun);
  4592. }
  4593. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4594. float * op_params = (float *)dst->op_params;
  4595. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4596. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4597. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CLAMP, {
  4598. (uint32_t)ggml_nelements(src0),
  4599. (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,
  4600. (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,
  4601. 0,
  4602. op_params[0], op_params[1],
  4603. }, dryrun);
  4604. }
  4605. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4606. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4607. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4608. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_PAD, {
  4609. (uint32_t)ggml_nelements(dst),
  4610. (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,
  4611. (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,
  4612. 0,
  4613. 0.0f, 0.0f,
  4614. }, dryrun);
  4615. }
  4616. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4617. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4618. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4619. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT, {
  4620. (uint32_t)ggml_nelements(dst),
  4621. (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,
  4622. (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,
  4623. 0,
  4624. 0.0f, 0.0f,
  4625. }, dryrun);
  4626. }
  4627. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4628. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4629. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4630. const uint32_t d_offset = ((vk_tensor_offset(dst) + dst->view_offs) % ctx->device->properties.limits.minStorageBufferOffsetAlignment) / dst_type_size;
  4631. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CPY, {
  4632. (uint32_t)ggml_nelements(src0),
  4633. (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,
  4634. (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,
  4635. d_offset,
  4636. 0.0f, 0.0f,
  4637. }, dryrun);
  4638. }
  4639. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4640. float * op_params = (float *)dst->op_params;
  4641. 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], op_params[0], 0.0f }, dryrun);
  4642. }
  4643. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4644. const int * int_op_params = (const int *)dst->op_params;
  4645. const float * float_op_params = (const float *)dst->op_params;
  4646. const uint32_t num_groups = int_op_params[0];
  4647. const float eps = float_op_params[1];
  4648. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  4649. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f }, dryrun);
  4650. }
  4651. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4652. float * op_params = (float *)dst->op_params;
  4653. 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 }, dryrun);
  4654. }
  4655. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4656. 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 }, dryrun);
  4657. }
  4658. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4659. int32_t * op_params = (int32_t *)dst->op_params;
  4660. 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] }, dryrun);
  4661. }
  4662. static void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4663. float * op_params = (float *)dst->op_params;
  4664. float scale = op_params[0];
  4665. float max_bias = op_params[1];
  4666. const uint32_t ncols = (uint32_t)src0->ne[0];
  4667. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  4668. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  4669. const uint32_t n_head_kv = nrows_x/nrows_y;
  4670. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  4671. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  4672. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  4673. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SOFT_MAX, {
  4674. ncols,
  4675. src1 != nullptr ? nrows_y : (uint32_t)0,
  4676. scale, max_bias,
  4677. m0, m1,
  4678. n_head_log2,
  4679. nrows_x,
  4680. }, dryrun);
  4681. }
  4682. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  4683. const int n_dims = ((int32_t *) dst->op_params)[1];
  4684. // const int mode = ((int32_t *) dst->op_params)[2];
  4685. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  4686. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  4687. const float freq_base = ((float *) dst->op_params)[5];
  4688. const float freq_scale = ((float *) dst->op_params)[6];
  4689. const float ext_factor = ((float *) dst->op_params)[7];
  4690. const float attn_factor = ((float *) dst->op_params)[8];
  4691. const float beta_fast = ((float *) dst->op_params)[9];
  4692. const float beta_slow = ((float *) dst->op_params)[10];
  4693. float corr_dims[2];
  4694. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  4695. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  4696. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ROPE, {
  4697. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  4698. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  4699. src2 != nullptr,
  4700. }, dryrun);
  4701. }
  4702. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4703. int32_t * op_params = (int32_t *)dst->op_params;
  4704. uint32_t ncols = src0->ne[0];
  4705. uint32_t ncols_pad = 1;
  4706. while (ncols_pad < ncols) {
  4707. ncols_pad *= 2;
  4708. }
  4709. GGML_ASSERT(ncols_pad <= 1024);
  4710. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  4711. ncols,
  4712. ncols_pad,
  4713. op_params[0],
  4714. }, dryrun);
  4715. }
  4716. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4717. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, { (uint32_t)src0->ne[0], 0, 0.0f, 0.0f }, dryrun);
  4718. }
  4719. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4720. const int32_t s0 = dst->op_params[0];
  4721. const int32_t s1 = dst->op_params[1];
  4722. const int32_t p0 = dst->op_params[2];
  4723. const int32_t p1 = dst->op_params[3];
  4724. const int32_t d0 = dst->op_params[4];
  4725. const int32_t d1 = dst->op_params[5];
  4726. const bool is_2D = dst->op_params[6] == 1;
  4727. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  4728. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  4729. const uint32_t IW = src1->ne[0];
  4730. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  4731. const uint32_t KW = src0->ne[0];
  4732. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  4733. const uint32_t OW = dst->ne[1];
  4734. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  4735. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  4736. const uint32_t pelements = OW * KW * KH;
  4737. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL, {
  4738. batch_offset, offset_delta,
  4739. IC, IW, IH, OW, OH, KW, KH,
  4740. pelements,
  4741. IC * KH * KW,
  4742. s0, s1, p0, p1, d0, d1,
  4743. }, dryrun);
  4744. }
  4745. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4746. const uint32_t dim = dst->op_params[0];
  4747. const uint32_t max_period = dst->op_params[1];
  4748. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  4749. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  4750. nb1, dim, max_period,
  4751. }, dryrun);
  4752. }
  4753. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4754. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  4755. const int32_t k1 = dst->op_params[1];
  4756. const int32_t k0 = dst->op_params[2];
  4757. const int32_t s1 = dst->op_params[3];
  4758. const int32_t s0 = dst->op_params[4];
  4759. const int32_t p1 = dst->op_params[5];
  4760. const int32_t p0 = dst->op_params[6];
  4761. const uint32_t IH = src0->ne[1];
  4762. const uint32_t IW = src0->ne[0];
  4763. const uint32_t N = dst->ne[3];
  4764. const uint32_t OC = dst->ne[2];
  4765. const uint32_t OH = dst->ne[1];
  4766. const uint32_t OW = dst->ne[0];
  4767. const uint32_t parallel_elements = N * OC * OH * OW;
  4768. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  4769. IW, IH, OW, OH, OC,
  4770. parallel_elements,
  4771. op,
  4772. k0, k1, s0, s1, p0, p1,
  4773. }, dryrun);
  4774. }
  4775. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4776. const float * op_params = (const float *)dst->op_params;
  4777. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f }, dryrun);
  4778. }
  4779. #ifdef GGML_VULKAN_RUN_TESTS
  4780. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  4781. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  4782. return;
  4783. }
  4784. i0 = std::max(i0, 5);
  4785. i1 = std::max(i1, 5);
  4786. i2 = std::max(i2, 0);
  4787. fprintf(stderr, " ");
  4788. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  4789. fprintf(stderr, "%7d ", idx1);
  4790. }
  4791. fprintf(stderr, "\n");
  4792. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  4793. fprintf(stderr, "%7d: ", idx0);
  4794. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  4795. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  4796. float val;
  4797. if (type == GGML_TYPE_F32) {
  4798. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  4799. } else if (type == GGML_TYPE_F16) {
  4800. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  4801. } else {
  4802. GGML_ABORT("fatal error");
  4803. }
  4804. fprintf(stderr, "% 7.2f ", val);
  4805. } else {
  4806. fprintf(stderr, " ");
  4807. }
  4808. }
  4809. fprintf(stderr, "\n");
  4810. }
  4811. }
  4812. template <typename X_TYPE, typename Y_TYPE>
  4813. 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) {
  4814. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  4815. const size_t x_ne = m * k * batch;
  4816. const size_t y_ne = k * n * batch;
  4817. const size_t d_ne = m * n * batch;
  4818. vk_pipeline p;
  4819. std::string shname;
  4820. if (shader_size == 0) {
  4821. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4822. p = ctx->device->pipeline_matmul_f32->a_s;
  4823. shname = "F32_ALIGNED_S";
  4824. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4825. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  4826. shname = "F32_F16_ALIGNED_S";
  4827. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4828. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  4829. shname = "F16_F32_ALIGNED_S";
  4830. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4831. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  4832. shname = "F16_ALIGNED_S";
  4833. } else {
  4834. GGML_ABORT("fatal error");
  4835. }
  4836. } else if (shader_size == 1) {
  4837. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4838. p = ctx->device->pipeline_matmul_f32->a_m;
  4839. shname = "F32_ALIGNED_M";
  4840. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4841. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  4842. shname = "F32_F16_ALIGNED_M";
  4843. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4844. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  4845. shname = "F16_F32_ALIGNED_M";
  4846. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4847. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  4848. shname = "F16_ALIGNED_M";
  4849. } else {
  4850. GGML_ABORT("fatal error");
  4851. }
  4852. } else if (shader_size == 2) {
  4853. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4854. p = ctx->device->pipeline_matmul_f32->a_l;
  4855. shname = "F32_ALIGNED_L";
  4856. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4857. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  4858. shname = "F32_F16_ALIGNED_L";
  4859. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4860. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  4861. shname = "F16_F32_ALIGNED_L";
  4862. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4863. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  4864. shname = "F16_ALIGNED_L";
  4865. } else {
  4866. GGML_ABORT("fatal error");
  4867. }
  4868. } else {
  4869. GGML_ASSERT(0);
  4870. }
  4871. const size_t kpad = ggml_vk_align_size(k, p->align);
  4872. if (k != kpad) {
  4873. if (shader_size == 0) {
  4874. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4875. p = ctx->device->pipeline_matmul_f32->s;
  4876. shname = "F32_S";
  4877. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4878. p = ctx->device->pipeline_matmul_f32_f16->s;
  4879. shname = "F32_F16_S";
  4880. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4881. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  4882. shname = "F16_F32_S";
  4883. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4884. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  4885. shname = "F16_S";
  4886. }
  4887. } else if (shader_size == 1) {
  4888. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4889. p = ctx->device->pipeline_matmul_f32->m;
  4890. shname = "F32_M";
  4891. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4892. p = ctx->device->pipeline_matmul_f32_f16->m;
  4893. shname = "F32_F16_M";
  4894. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4895. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  4896. shname = "F16_F32_M";
  4897. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4898. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  4899. shname = "F16_M";
  4900. }
  4901. } else if (shader_size == 2) {
  4902. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4903. p = ctx->device->pipeline_matmul_f32->l;
  4904. shname = "F32_L";
  4905. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4906. p = ctx->device->pipeline_matmul_f32_f16->l;
  4907. shname = "F32_F16_L";
  4908. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  4909. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  4910. shname = "F16_F32_L";
  4911. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4912. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  4913. shname = "F16_L";
  4914. }
  4915. }
  4916. }
  4917. ggml_pipeline_request_descriptor_sets(ctx->device, p, num_it);
  4918. if (split_k > 1) {
  4919. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  4920. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  4921. // Resize buffer
  4922. if (ctx->prealloc_split_k != nullptr) {
  4923. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  4924. }
  4925. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  4926. }
  4927. }
  4928. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  4929. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  4930. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  4931. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  4932. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  4933. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  4934. float* d = (float *) malloc(sizeof(float) * d_ne);
  4935. for (size_t i = 0; i < x_ne; i++) {
  4936. if (std::is_same<float, X_TYPE>()) {
  4937. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  4938. // x[i] = 1.0f;
  4939. // x[i] = i + 1;
  4940. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  4941. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  4942. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  4943. // x[i] = ggml_fp32_to_fp16(1.0f);
  4944. // x[i] = ggml_fp32_to_fp16(i + 1);
  4945. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  4946. } else {
  4947. GGML_ABORT("fatal error");
  4948. }
  4949. }
  4950. for (size_t i = 0; i < y_ne; i++) {
  4951. if (std::is_same<float, Y_TYPE>()) {
  4952. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  4953. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  4954. // y[i] = i + 1;
  4955. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  4956. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  4957. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  4958. // y[i] = ggml_fp32_to_fp16(i + 1);
  4959. } else {
  4960. GGML_ABORT("fatal error");
  4961. }
  4962. }
  4963. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  4964. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  4965. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  4966. ggml_vk_ctx_begin(ctx->device, subctx);
  4967. for (size_t i = 0; i < num_it; i++) {
  4968. ggml_vk_matmul(
  4969. 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),
  4970. m, n, k,
  4971. k, k, m, k*m, k*n, m*n,
  4972. split_k, batch, batch, batch, 1, 1
  4973. );
  4974. }
  4975. ggml_vk_ctx_end(subctx);
  4976. auto begin = std::chrono::high_resolution_clock::now();
  4977. ggml_vk_submit(subctx, ctx->fence);
  4978. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  4979. ctx->device->device.resetFences({ ctx->fence });
  4980. auto end = std::chrono::high_resolution_clock::now();
  4981. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  4982. // copy dst to host
  4983. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  4984. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  4985. ggml_init_params iparams = {
  4986. /*.mem_size =*/ 1024*1024*1024,
  4987. /*.mem_buffer =*/ NULL,
  4988. /*.no_alloc =*/ true,
  4989. };
  4990. ggml_context * ggml_ctx = ggml_init(iparams);
  4991. ggml_type src0_type;
  4992. ggml_type src1_type;
  4993. if (std::is_same<float, X_TYPE>()) {
  4994. src0_type = GGML_TYPE_F32;
  4995. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  4996. src0_type = GGML_TYPE_F16;
  4997. } else {
  4998. GGML_ABORT("fatal error");
  4999. }
  5000. if (std::is_same<float, Y_TYPE>()) {
  5001. src1_type = GGML_TYPE_F32;
  5002. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5003. src1_type = GGML_TYPE_F16;
  5004. } else {
  5005. GGML_ABORT("fatal error");
  5006. }
  5007. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  5008. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  5009. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  5010. src0_ggml->data = x;
  5011. src1_ggml->data = y;
  5012. tensor_ggml->data = d_chk;
  5013. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5014. ggml_build_forward_expand(cgraph, tensor_ggml);
  5015. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  5016. ggml_free(ggml_ctx);
  5017. double avg_err = 0.0;
  5018. int first_err_n = -1;
  5019. int first_err_m = -1;
  5020. int first_err_b = -1;
  5021. for (size_t i = 0; i < m*n*batch; i++) {
  5022. double err = std::fabs(d[i] - d_chk[i]);
  5023. avg_err += err;
  5024. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  5025. first_err_b = i / (m * n);
  5026. first_err_n = (i % (m * n)) / m;
  5027. first_err_m = (i % (m * n)) % m;
  5028. }
  5029. }
  5030. avg_err /= m * n;
  5031. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  5032. std::cerr << "TEST " << shname << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time / num_it << "ms " << tflops << " TFLOPS avg_err=" << avg_err << std::endl;
  5033. if (avg_err > 0.1 || std::isnan(avg_err)) {
  5034. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  5035. std::cerr << "Actual result: " << std::endl << std::endl;
  5036. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5037. std::cerr << "Expected result: " << std::endl << std::endl;
  5038. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5039. if (split_k > 1) {
  5040. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  5041. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  5042. std::cerr << "d_buf0: " << std::endl << std::endl;
  5043. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5044. std::cerr << "d_buf1: " << std::endl << std::endl;
  5045. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5046. std::cerr << "d_buf2: " << std::endl << std::endl;
  5047. 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);
  5048. std::cerr << "d_buf3: " << std::endl << std::endl;
  5049. 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);
  5050. free(split_k_buf);
  5051. }
  5052. }
  5053. free(d_chk);
  5054. ggml_vk_queue_cleanup(ctx->device, ctx->device->transfer_queue);
  5055. ggml_vk_queue_cleanup(ctx->device, ctx->device->compute_queue);
  5056. ggml_vk_destroy_buffer(d_X);
  5057. ggml_vk_destroy_buffer(d_Y);
  5058. ggml_vk_destroy_buffer(d_D);
  5059. ggml_pipeline_cleanup(p);
  5060. ggml_pipeline_cleanup(ctx->device->pipeline_matmul_split_k_reduce);
  5061. free(x);
  5062. free(y);
  5063. free(d);
  5064. }
  5065. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  5066. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  5067. return;
  5068. }
  5069. i0 = std::max(i0, 5);
  5070. i1 = std::max(i1, 5);
  5071. i2 = std::max(i2, 0);
  5072. i3 = std::max(i3, 0);
  5073. fprintf(stderr, " ");
  5074. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5075. fprintf(stderr, "%7d ", idx1);
  5076. }
  5077. fprintf(stderr, "\n");
  5078. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  5079. fprintf(stderr, "%7d: ", idx0);
  5080. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5081. 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]) {
  5082. float val;
  5083. if (tensor->type == GGML_TYPE_F32) {
  5084. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  5085. } else if (tensor->type == GGML_TYPE_F16) {
  5086. 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]));
  5087. } else {
  5088. GGML_ABORT("fatal error");
  5089. }
  5090. fprintf(stderr, "% 7.2f ", val);
  5091. } else {
  5092. fprintf(stderr, " ");
  5093. }
  5094. }
  5095. fprintf(stderr, "\n");
  5096. }
  5097. }
  5098. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  5099. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  5100. }
  5101. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  5102. if (quant == GGML_TYPE_F32) {
  5103. memcpy(to, from, sizeof(float) * ne);
  5104. return;
  5105. }
  5106. const auto * tt = ggml_get_type_traits(quant);
  5107. ggml_to_float_t dequant_fn = tt->to_float;
  5108. dequant_fn(from, to, ne);
  5109. }
  5110. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  5111. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  5112. const size_t x_sz = sizeof(float) * ne;
  5113. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  5114. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  5115. float * x = (float *) malloc(x_sz);
  5116. void * qx = malloc(qx_sz);
  5117. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5118. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5119. float * x_ref = (float *) malloc(x_sz);
  5120. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  5121. for (size_t i = 0; i < ne; i++) {
  5122. x[i] = rand() / (float)RAND_MAX;
  5123. }
  5124. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  5125. ggml_vk_quantize_data(x, qx, ne, quant);
  5126. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  5127. ggml_pipeline_request_descriptor_sets(ctx->device, p, 1);
  5128. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5129. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  5130. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5131. ggml_vk_ctx_begin(ctx->device, subctx);
  5132. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  5133. ggml_vk_dispatch_pipeline(ctx, subctx, p, { vk_subbuffer{ qx_buf, 0, qx_sz }, vk_subbuffer{ x_buf, 0, x_sz_f16 } }, pc.size() * sizeof(int), pc.data(), { (uint32_t)ne, 1, 1});
  5134. ggml_vk_ctx_end(subctx);
  5135. auto begin = std::chrono::high_resolution_clock::now();
  5136. ggml_vk_submit(subctx, ctx->fence);
  5137. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  5138. ctx->device->device.resetFences({ ctx->fence });
  5139. auto end = std::chrono::high_resolution_clock::now();
  5140. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5141. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  5142. int first_err = -1;
  5143. double avg_err = 0.0;
  5144. for (size_t i = 0; i < ne; i++) {
  5145. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  5146. avg_err += error;
  5147. if (first_err < 0 && error > 0.05) {
  5148. first_err = i;
  5149. }
  5150. }
  5151. avg_err /= ne;
  5152. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  5153. if (avg_err > 0.1) {
  5154. std::cerr << "first_error = " << first_err << std::endl;
  5155. std::cerr << "Actual result: " << std::endl << std::endl;
  5156. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  5157. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  5158. }
  5159. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  5160. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  5161. std::cerr << x_ref[i] << ", ";
  5162. }
  5163. std::cerr << std::endl;
  5164. }
  5165. ggml_vk_destroy_buffer(x_buf);
  5166. ggml_vk_destroy_buffer(qx_buf);
  5167. free(x);
  5168. free(qx);
  5169. free(x_ref);
  5170. free(x_chk);
  5171. }
  5172. 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) {
  5173. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  5174. const size_t x_ne = m * k * batch;
  5175. const size_t y_ne = k * n * batch;
  5176. const size_t d_ne = m * n * batch;
  5177. vk_pipeline p;
  5178. std::string shname;
  5179. if (shader_size == 0) {
  5180. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_s : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_s;
  5181. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  5182. } else if (shader_size == 1) {
  5183. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_m : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_m;
  5184. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  5185. } else if (shader_size == 2) {
  5186. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_l : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_l;
  5187. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  5188. } else {
  5189. GGML_ASSERT(0);
  5190. }
  5191. const size_t kpad = ggml_vk_align_size(k, p->align);
  5192. if (k != kpad) {
  5193. if (shader_size == 0) {
  5194. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->s : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->s;
  5195. shname = std::string(ggml_type_name(quant)) + "_S";
  5196. } else if (shader_size == 1) {
  5197. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->m : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->m;
  5198. shname = std::string(ggml_type_name(quant)) + "_M";
  5199. } else if (shader_size == 2) {
  5200. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->l : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->l;
  5201. shname = std::string(ggml_type_name(quant)) + "_L";
  5202. } else {
  5203. GGML_ASSERT(0);
  5204. }
  5205. }
  5206. const size_t x_sz = sizeof(float) * x_ne;
  5207. const size_t y_sz = sizeof(float) * y_ne;
  5208. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  5209. const size_t d_sz = sizeof(float) * d_ne;
  5210. float * x = (float *) malloc(x_sz);
  5211. float * y = (float *) malloc(y_sz);
  5212. void * qx = malloc(qx_sz);
  5213. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5214. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5215. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5216. float * d = (float *) malloc(d_sz);
  5217. float * d_chk = (float *) malloc(d_sz);
  5218. for (size_t i = 0; i < x_ne; i++) {
  5219. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  5220. }
  5221. ggml_vk_quantize_data(x, qx, x_ne, quant);
  5222. for (size_t i = 0; i < y_ne; i++) {
  5223. // y[i] = rand() / (float)RAND_MAX;
  5224. y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  5225. }
  5226. ggml_pipeline_request_descriptor_sets(ctx->device, p, num_it);
  5227. if (split_k > 1) {
  5228. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  5229. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  5230. // Resize buffer
  5231. if (ctx->prealloc_split_k != nullptr) {
  5232. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5233. }
  5234. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5235. }
  5236. }
  5237. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5238. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  5239. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  5240. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5241. ggml_vk_ctx_begin(ctx->device, subctx);
  5242. for (size_t i = 0; i < num_it; i++) {
  5243. ggml_vk_matmul(
  5244. 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),
  5245. m, n, k,
  5246. k, k, m, k*m, k*n, m*n,
  5247. split_k, batch, batch, batch, 1, 1
  5248. );
  5249. }
  5250. ggml_vk_ctx_end(subctx);
  5251. auto begin = std::chrono::high_resolution_clock::now();
  5252. ggml_vk_submit(subctx, ctx->fence);
  5253. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  5254. ctx->device->device.resetFences({ ctx->fence });
  5255. auto end = std::chrono::high_resolution_clock::now();
  5256. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5257. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  5258. ggml_init_params iparams = {
  5259. /*.mem_size =*/ 1024*1024*1024,
  5260. /*.mem_buffer =*/ NULL,
  5261. /*.no_alloc =*/ true,
  5262. };
  5263. ggml_context * ggml_ctx = ggml_init(iparams);
  5264. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  5265. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  5266. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  5267. src0_ggml->data = qx;
  5268. src1_ggml->data = y;
  5269. tensor_ggml->data = d_chk;
  5270. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5271. ggml_build_forward_expand(cgraph, tensor_ggml);
  5272. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  5273. ggml_free(ggml_ctx);
  5274. double avg_err = 0.0;
  5275. int first_err_n = -1;
  5276. int first_err_m = -1;
  5277. int first_err_b = -1;
  5278. for (size_t i = 0; i < m*n*batch; i++) {
  5279. double err = std::fabs(d[i] - d_chk[i]);
  5280. avg_err += err;
  5281. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  5282. first_err_b = i / (m * n);
  5283. first_err_n = (i % (m * n)) / m;
  5284. first_err_m = (i % (m * n)) % m;
  5285. }
  5286. }
  5287. avg_err /= m * n;
  5288. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  5289. std::cerr << "TEST MMQ " << shname << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time_ms / num_it << "ms " << tflops << " TFLOPS avg_err=" << avg_err << std::endl;
  5290. if (avg_err > 0.01 || std::isnan(avg_err)) {
  5291. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  5292. std::cerr << "Actual result: " << std::endl << std::endl;
  5293. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5294. std::cerr << std::endl;
  5295. std::cerr << "Expected result: " << std::endl << std::endl;
  5296. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5297. if (split_k > 1) {
  5298. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  5299. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  5300. std::cerr << "d_buf0: " << std::endl << std::endl;
  5301. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5302. std::cerr << "d_buf1: " << std::endl << std::endl;
  5303. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5304. std::cerr << "d_buf2: " << std::endl << std::endl;
  5305. 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);
  5306. std::cerr << "d_buf3: " << std::endl << std::endl;
  5307. 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);
  5308. free(split_k_buf);
  5309. }
  5310. }
  5311. ggml_vk_destroy_buffer(qx_buf);
  5312. ggml_vk_destroy_buffer(y_buf);
  5313. ggml_vk_destroy_buffer(d_buf);
  5314. free(x);
  5315. free(qx);
  5316. free(y);
  5317. free(d);
  5318. free(d_chk);
  5319. }
  5320. #endif
  5321. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  5322. #if defined(GGML_VULKAN_RUN_TESTS)
  5323. const std::vector<size_t> vals {
  5324. 512, 512, 128,
  5325. 128, 512, 512,
  5326. 4096, 512, 4096,
  5327. 11008, 512, 4096,
  5328. 4096, 512, 11008,
  5329. 32000, 512, 4096,
  5330. 8, 8, 8,
  5331. 100, 46, 576,
  5332. 623, 111, 128,
  5333. 100, 46, 558,
  5334. 512, 1, 256,
  5335. 128, 110, 622,
  5336. 511, 511, 127,
  5337. 511, 511, 7,
  5338. 511, 511, 17,
  5339. 49, 49, 128,
  5340. 128, 49, 49,
  5341. 4096, 49, 4096,
  5342. };
  5343. const size_t num_it = 100;
  5344. for (size_t i = 0; i < vals.size(); i += 3) {
  5345. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  5346. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  5347. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  5348. std::cerr << '\n';
  5349. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  5350. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  5351. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  5352. std::cerr << '\n';
  5353. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  5354. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  5355. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  5356. std::cerr << '\n' << std::endl;
  5357. if (vals[i + 2] % 32 == 0) {
  5358. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  5359. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  5360. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  5361. std::cerr << '\n';
  5362. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  5363. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  5364. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  5365. std::cerr << '\n';
  5366. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  5367. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  5368. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  5369. std::cerr << '\n' << std::endl;
  5370. }
  5371. if (vals[i + 2] % 256 == 0) {
  5372. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  5373. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  5374. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  5375. std::cerr << '\n';
  5376. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  5377. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  5378. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  5379. std::cerr << '\n';
  5380. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  5381. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  5382. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  5383. std::cerr << '\n' << std::endl;
  5384. }
  5385. }
  5386. GGML_ABORT("fatal error");
  5387. #endif
  5388. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  5389. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  5390. // Resize buffer
  5391. if (ctx->prealloc_x != nullptr) {
  5392. ggml_vk_destroy_buffer(ctx->prealloc_x);
  5393. }
  5394. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  5395. }
  5396. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  5397. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  5398. // Resize buffer
  5399. if (ctx->prealloc_y != nullptr) {
  5400. ggml_vk_destroy_buffer(ctx->prealloc_y);
  5401. }
  5402. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  5403. }
  5404. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  5405. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  5406. // Resize buffer
  5407. if (ctx->prealloc_split_k != nullptr) {
  5408. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5409. }
  5410. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  5411. }
  5412. }
  5413. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_tensor* tensor, int tensor_idx, bool use_fence);
  5414. // Returns true if node has enqueued work into the queue, false otherwise
  5415. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  5416. static bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_tensor * node, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool dryrun, bool last_node, bool submit){
  5417. if (ggml_is_empty(node) || !node->buffer) {
  5418. return false;
  5419. }
  5420. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  5421. ctx->semaphore_idx = 0;
  5422. const ggml_tensor * src0 = node->src[0];
  5423. const ggml_tensor * src1 = node->src[1];
  5424. const ggml_tensor * src2 = node->src[2];
  5425. const ggml_tensor * src3 = node->src[3];
  5426. switch (node->op) {
  5427. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  5428. case GGML_OP_RESHAPE:
  5429. case GGML_OP_VIEW:
  5430. case GGML_OP_PERMUTE:
  5431. case GGML_OP_TRANSPOSE:
  5432. case GGML_OP_NONE:
  5433. return false;
  5434. case GGML_OP_UNARY:
  5435. switch (ggml_get_unary_op(node)) {
  5436. case GGML_UNARY_OP_SILU:
  5437. case GGML_UNARY_OP_GELU:
  5438. case GGML_UNARY_OP_GELU_QUICK:
  5439. case GGML_UNARY_OP_RELU:
  5440. case GGML_UNARY_OP_TANH:
  5441. break;
  5442. default:
  5443. return false;
  5444. }
  5445. break;
  5446. case GGML_OP_REPEAT:
  5447. case GGML_OP_GET_ROWS:
  5448. case GGML_OP_ADD:
  5449. case GGML_OP_ACC:
  5450. case GGML_OP_MUL:
  5451. case GGML_OP_DIV:
  5452. case GGML_OP_CONCAT:
  5453. case GGML_OP_UPSCALE:
  5454. case GGML_OP_SCALE:
  5455. case GGML_OP_SQR:
  5456. case GGML_OP_SIN:
  5457. case GGML_OP_COS:
  5458. case GGML_OP_CLAMP:
  5459. case GGML_OP_PAD:
  5460. case GGML_OP_CPY:
  5461. case GGML_OP_CONT:
  5462. case GGML_OP_DUP:
  5463. case GGML_OP_NORM:
  5464. case GGML_OP_GROUP_NORM:
  5465. case GGML_OP_RMS_NORM:
  5466. case GGML_OP_DIAG_MASK_INF:
  5467. case GGML_OP_SOFT_MAX:
  5468. case GGML_OP_ROPE:
  5469. case GGML_OP_MUL_MAT:
  5470. case GGML_OP_MUL_MAT_ID:
  5471. case GGML_OP_ARGSORT:
  5472. case GGML_OP_SUM_ROWS:
  5473. case GGML_OP_IM2COL:
  5474. case GGML_OP_TIMESTEP_EMBEDDING:
  5475. case GGML_OP_POOL_2D:
  5476. case GGML_OP_LEAKY_RELU:
  5477. case GGML_OP_FLASH_ATTN_EXT:
  5478. break;
  5479. default:
  5480. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  5481. GGML_ABORT("fatal error");
  5482. return false;
  5483. }
  5484. vk_context compute_ctx;
  5485. if (!dryrun) {
  5486. if (ctx->compute_ctx.expired()) {
  5487. compute_ctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5488. ctx->compute_ctx = compute_ctx;
  5489. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  5490. } else {
  5491. compute_ctx = ctx->compute_ctx.lock();
  5492. }
  5493. } else {
  5494. switch (node->op) {
  5495. case GGML_OP_REPEAT:
  5496. case GGML_OP_ACC:
  5497. case GGML_OP_GET_ROWS:
  5498. case GGML_OP_ADD:
  5499. case GGML_OP_MUL:
  5500. case GGML_OP_DIV:
  5501. case GGML_OP_CONCAT:
  5502. case GGML_OP_UPSCALE:
  5503. case GGML_OP_SCALE:
  5504. case GGML_OP_SQR:
  5505. case GGML_OP_SIN:
  5506. case GGML_OP_COS:
  5507. case GGML_OP_CLAMP:
  5508. case GGML_OP_PAD:
  5509. case GGML_OP_CPY:
  5510. case GGML_OP_CONT:
  5511. case GGML_OP_DUP:
  5512. case GGML_OP_NORM:
  5513. case GGML_OP_GROUP_NORM:
  5514. case GGML_OP_RMS_NORM:
  5515. case GGML_OP_UNARY:
  5516. case GGML_OP_DIAG_MASK_INF:
  5517. case GGML_OP_SOFT_MAX:
  5518. case GGML_OP_ROPE:
  5519. case GGML_OP_ARGSORT:
  5520. case GGML_OP_SUM_ROWS:
  5521. case GGML_OP_IM2COL:
  5522. case GGML_OP_TIMESTEP_EMBEDDING:
  5523. case GGML_OP_POOL_2D:
  5524. case GGML_OP_LEAKY_RELU:
  5525. {
  5526. // These operations all go through ggml_vk_op_f32, so short-circuit and
  5527. // do the only thing needed for the dryrun.
  5528. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  5529. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  5530. return false;
  5531. }
  5532. default:
  5533. break;
  5534. }
  5535. }
  5536. switch (node->op) {
  5537. case GGML_OP_REPEAT:
  5538. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  5539. break;
  5540. case GGML_OP_ACC:
  5541. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  5542. break;
  5543. case GGML_OP_GET_ROWS:
  5544. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  5545. break;
  5546. case GGML_OP_ADD:
  5547. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  5548. break;
  5549. case GGML_OP_MUL:
  5550. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  5551. break;
  5552. case GGML_OP_DIV:
  5553. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  5554. break;
  5555. case GGML_OP_CONCAT:
  5556. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  5557. break;
  5558. case GGML_OP_UPSCALE:
  5559. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  5560. break;
  5561. case GGML_OP_SCALE:
  5562. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  5563. break;
  5564. case GGML_OP_SQR:
  5565. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  5566. break;
  5567. case GGML_OP_SIN:
  5568. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  5569. break;
  5570. case GGML_OP_COS:
  5571. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  5572. break;
  5573. case GGML_OP_CLAMP:
  5574. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  5575. break;
  5576. case GGML_OP_PAD:
  5577. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  5578. break;
  5579. case GGML_OP_CPY:
  5580. case GGML_OP_CONT:
  5581. case GGML_OP_DUP:
  5582. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  5583. break;
  5584. case GGML_OP_NORM:
  5585. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  5586. break;
  5587. case GGML_OP_GROUP_NORM:
  5588. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  5589. break;
  5590. case GGML_OP_RMS_NORM:
  5591. ggml_vk_rms_norm(ctx, compute_ctx, src0, node, dryrun);
  5592. break;
  5593. case GGML_OP_UNARY:
  5594. switch (ggml_get_unary_op(node)) {
  5595. case GGML_UNARY_OP_SILU:
  5596. case GGML_UNARY_OP_GELU:
  5597. case GGML_UNARY_OP_GELU_QUICK:
  5598. case GGML_UNARY_OP_RELU:
  5599. case GGML_UNARY_OP_TANH:
  5600. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  5601. break;
  5602. default:
  5603. return false;
  5604. }
  5605. break;
  5606. case GGML_OP_DIAG_MASK_INF:
  5607. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  5608. break;
  5609. case GGML_OP_SOFT_MAX:
  5610. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, node, dryrun);
  5611. break;
  5612. case GGML_OP_ROPE:
  5613. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  5614. break;
  5615. case GGML_OP_ARGSORT:
  5616. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  5617. break;
  5618. case GGML_OP_SUM_ROWS:
  5619. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  5620. break;
  5621. case GGML_OP_IM2COL:
  5622. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  5623. break;
  5624. case GGML_OP_TIMESTEP_EMBEDDING:
  5625. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  5626. break;
  5627. case GGML_OP_POOL_2D:
  5628. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  5629. break;
  5630. case GGML_OP_LEAKY_RELU:
  5631. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  5632. break;
  5633. case GGML_OP_MUL_MAT:
  5634. ggml_vk_mul_mat(ctx, compute_ctx, src0, src1, node, dryrun);
  5635. break;
  5636. case GGML_OP_MUL_MAT_ID:
  5637. ggml_vk_mul_mat_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  5638. break;
  5639. case GGML_OP_FLASH_ATTN_EXT:
  5640. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node, dryrun);
  5641. break;
  5642. default:
  5643. return false;
  5644. }
  5645. if (dryrun) {
  5646. return false;
  5647. }
  5648. ctx->tensor_ctxs[node_idx] = compute_ctx;
  5649. #if defined(GGML_VULKAN_CHECK_RESULTS) || defined(GGML_VULKAN_PERF)
  5650. // Force context reset on each node so that each tensor ends up in its own context
  5651. // and can be run and compared to its CPU equivalent separately
  5652. last_node = true;
  5653. #endif
  5654. if (submit || last_node) {
  5655. ggml_vk_ctx_end(compute_ctx);
  5656. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  5657. if (last_node) {
  5658. compute_ctx->exit_tensor_idx = node_idx_begin;
  5659. }
  5660. else {
  5661. compute_ctx->exit_tensor_idx = -1;
  5662. }
  5663. ctx->compute_ctx.reset();
  5664. bool ok = ggml_vk_compute_forward(ctx, node_begin, node_idx_begin, false);
  5665. if (!ok) {
  5666. if (node->op == GGML_OP_UNARY) {
  5667. std::cerr << __func__ << ": error: op not supported UNARY " << node->name << " (" << ggml_unary_op_name(static_cast<ggml_unary_op>(node->op_params[0])) << ")" << std::endl;
  5668. }
  5669. else {
  5670. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  5671. }
  5672. }
  5673. }
  5674. return true;
  5675. }
  5676. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_tensor * tensor, int tensor_idx, bool use_fence = true){
  5677. ggml_backend_buffer * buf = nullptr;
  5678. switch (tensor->op) {
  5679. case GGML_OP_ADD:
  5680. case GGML_OP_ACC:
  5681. case GGML_OP_GET_ROWS:
  5682. case GGML_OP_MUL:
  5683. case GGML_OP_DIV:
  5684. case GGML_OP_CONCAT:
  5685. case GGML_OP_UPSCALE:
  5686. case GGML_OP_SCALE:
  5687. case GGML_OP_SQR:
  5688. case GGML_OP_SIN:
  5689. case GGML_OP_COS:
  5690. case GGML_OP_CLAMP:
  5691. case GGML_OP_PAD:
  5692. case GGML_OP_CPY:
  5693. case GGML_OP_CONT:
  5694. case GGML_OP_DUP:
  5695. case GGML_OP_NORM:
  5696. case GGML_OP_GROUP_NORM:
  5697. case GGML_OP_RMS_NORM:
  5698. case GGML_OP_DIAG_MASK_INF:
  5699. case GGML_OP_SOFT_MAX:
  5700. case GGML_OP_ROPE:
  5701. case GGML_OP_RESHAPE:
  5702. case GGML_OP_VIEW:
  5703. case GGML_OP_PERMUTE:
  5704. case GGML_OP_TRANSPOSE:
  5705. case GGML_OP_NONE:
  5706. case GGML_OP_ARGSORT:
  5707. case GGML_OP_SUM_ROWS:
  5708. case GGML_OP_IM2COL:
  5709. case GGML_OP_TIMESTEP_EMBEDDING:
  5710. case GGML_OP_POOL_2D:
  5711. case GGML_OP_LEAKY_RELU:
  5712. case GGML_OP_REPEAT:
  5713. buf = tensor->buffer;
  5714. break;
  5715. case GGML_OP_UNARY:
  5716. switch (ggml_get_unary_op(tensor)) {
  5717. case GGML_UNARY_OP_SILU:
  5718. case GGML_UNARY_OP_GELU:
  5719. case GGML_UNARY_OP_GELU_QUICK:
  5720. case GGML_UNARY_OP_RELU:
  5721. case GGML_UNARY_OP_TANH:
  5722. buf = tensor->buffer;
  5723. break;
  5724. default:
  5725. return false;
  5726. }
  5727. break;
  5728. case GGML_OP_MUL_MAT:
  5729. case GGML_OP_MUL_MAT_ID:
  5730. case GGML_OP_FLASH_ATTN_EXT:
  5731. buf = tensor->buffer;
  5732. break;
  5733. default:
  5734. return false;
  5735. }
  5736. if (buf == nullptr) {
  5737. return false;
  5738. }
  5739. VK_LOG_DEBUG("ggml_vk_compute_forward(" << tensor << ", name=" << tensor->name << ", op=" << ggml_op_name(tensor->op) << ", type=" << tensor->type << ", ne0=" << tensor->ne[0] << ", ne1=" << tensor->ne[1] << ", ne2=" << tensor->ne[2] << ", ne3=" << tensor->ne[3] << ", nb0=" << tensor->nb[0] << ", nb1=" << tensor->nb[1] << ", nb2=" << tensor->nb[2] << ", nb3=" << tensor->nb[3] << ", view_src=" << tensor->view_src << ", view_offs=" << tensor->view_offs << ")");
  5740. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  5741. // always wait for the GPU work to be done for the last submit
  5742. if (tensor_idx == subctx->exit_tensor_idx) {
  5743. use_fence = true;
  5744. }
  5745. // Only run if ctx hasn't been submitted yet
  5746. if (!subctx->seqs.empty()) {
  5747. #ifdef GGML_VULKAN_CHECK_RESULTS
  5748. ggml_vk_check_results_0(tensor);
  5749. use_fence = true;
  5750. #endif
  5751. // Do staging buffer copies
  5752. for (auto& cpy : subctx->in_memcpys) {
  5753. memcpy(cpy.dst, cpy.src, cpy.n);
  5754. }
  5755. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  5756. if (use_fence) {
  5757. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_compute_forward waitForFences");
  5758. ctx->device->device.resetFences({ ctx->fence });
  5759. }
  5760. #ifdef GGML_VULKAN_CHECK_RESULTS
  5761. ggml_vk_check_results_1(tensor);
  5762. #endif
  5763. }
  5764. if (tensor_idx == subctx->exit_tensor_idx) {
  5765. // Do staging buffer copies
  5766. for (auto& cpy : subctx->out_memcpys) {
  5767. memcpy(cpy.dst, cpy.src, cpy.n);
  5768. }
  5769. subctx->in_memcpys.clear();
  5770. subctx->out_memcpys.clear();
  5771. }
  5772. return true;
  5773. }
  5774. // Clean up after graph processing is done
  5775. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  5776. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  5777. for (auto& buffer : ctx->gc.temp_buffers) {
  5778. ggml_vk_pool_free(ctx, buffer);
  5779. }
  5780. ctx->gc.temp_buffers.clear();
  5781. for (auto& dsr : ctx->device->pipeline_descriptor_set_requirements) {
  5782. vk_pipeline_ref plr = ctx->device->pipelines[dsr.first];
  5783. if (plr.expired()) {
  5784. continue;
  5785. }
  5786. vk_pipeline pl = plr.lock();
  5787. ggml_pipeline_cleanup(pl);
  5788. }
  5789. ggml_vk_queue_cleanup(ctx->device, ctx->device->compute_queue);
  5790. ggml_vk_queue_cleanup(ctx->device, ctx->device->transfer_queue);
  5791. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  5792. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  5793. }
  5794. ctx->gc.semaphores.clear();
  5795. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  5796. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  5797. }
  5798. ctx->gc.tl_semaphores.clear();
  5799. ctx->semaphore_idx = 0;
  5800. ctx->event_idx = 0;
  5801. for (auto& event : ctx->gc.events) {
  5802. ctx->device->device.resetEvent(event);
  5803. }
  5804. ctx->tensor_ctxs.clear();
  5805. ctx->gc.contexts.clear();
  5806. ctx->device->pipeline_descriptor_set_requirements.clear();
  5807. }
  5808. // Clean up on backend free
  5809. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  5810. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  5811. ggml_vk_graph_cleanup(ctx);
  5812. ggml_vk_destroy_buffer(ctx->prealloc_x);
  5813. ggml_vk_destroy_buffer(ctx->prealloc_y);
  5814. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5815. for (auto& buffer : ctx->buffer_pool) {
  5816. ggml_vk_destroy_buffer(buffer);
  5817. }
  5818. ctx->prealloc_size_x = 0;
  5819. ctx->prealloc_size_y = 0;
  5820. ctx->prealloc_size_split_k = 0;
  5821. for (auto& event : ctx->gc.events) {
  5822. ctx->device->device.destroyEvent(event);
  5823. }
  5824. ctx->gc.events.clear();
  5825. ctx->device->device.destroyFence(ctx->fence);
  5826. }
  5827. static int ggml_vk_get_device_count() {
  5828. ggml_vk_instance_init();
  5829. return vk_instance.device_indices.size();
  5830. }
  5831. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  5832. ggml_vk_instance_init();
  5833. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  5834. vk::PhysicalDeviceProperties props;
  5835. devices[device].getProperties(&props);
  5836. snprintf(description, description_size, "%s", props.deviceName.data());
  5837. }
  5838. // backend interface
  5839. #define UNUSED GGML_UNUSED
  5840. // device backend
  5841. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  5842. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  5843. }
  5844. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  5845. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  5846. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  5847. ggml_vk_destroy_buffer(ctx->dev_buffer);
  5848. delete ctx;
  5849. }
  5850. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  5851. return vk_ptr_base;
  5852. UNUSED(buffer);
  5853. }
  5854. static void ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  5855. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  5856. if (tensor->view_src != nullptr) {
  5857. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  5858. }
  5859. }
  5860. 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) {
  5861. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  5862. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  5863. vk_buffer buf = buf_ctx->dev_buffer;
  5864. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  5865. }
  5866. 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) {
  5867. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  5868. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  5869. vk_buffer buf = buf_ctx->dev_buffer;
  5870. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  5871. }
  5872. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  5873. if (ggml_backend_buffer_is_vk(src->buffer)) {
  5874. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  5875. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5876. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  5877. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  5878. ggml_vk_buffer_copy(dst_buf, vk_tensor_offset(dst) + dst->view_offs, src_buf, vk_tensor_offset(src) + src->view_offs, ggml_nbytes(src));
  5879. return true;
  5880. }
  5881. return false;
  5882. UNUSED(buffer);
  5883. }
  5884. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  5885. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  5886. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  5887. }
  5888. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  5889. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  5890. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  5891. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  5892. /* .memset_tensor = */ NULL,
  5893. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  5894. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  5895. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  5896. /* .clear = */ ggml_backend_vk_buffer_clear,
  5897. /* .reset = */ NULL,
  5898. };
  5899. // vk buffer type
  5900. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  5901. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  5902. return ctx->name.c_str();
  5903. }
  5904. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  5905. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  5906. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  5907. vk_buffer dev_buffer = nullptr;
  5908. try {
  5909. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  5910. } catch (const vk::SystemError& e) {
  5911. return nullptr;
  5912. }
  5913. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  5914. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  5915. }
  5916. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  5917. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  5918. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5919. }
  5920. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  5921. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  5922. return ctx->device->max_memory_allocation_size;
  5923. }
  5924. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  5925. return ggml_nbytes(tensor);
  5926. UNUSED(buft);
  5927. }
  5928. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  5929. ggml_vk_instance_init();
  5930. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  5931. vk_device dev = ggml_vk_get_device(dev_num);
  5932. return &dev->buffer_type;
  5933. }
  5934. // host buffer type
  5935. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  5936. return GGML_VK_NAME "_Host";
  5937. UNUSED(buft);
  5938. }
  5939. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  5940. return GGML_VK_NAME "_Host";
  5941. UNUSED(buffer);
  5942. }
  5943. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  5944. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  5945. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  5946. }
  5947. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  5948. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  5949. size += 32; // Behave like the CPU buffer type
  5950. void * ptr = nullptr;
  5951. try {
  5952. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  5953. } catch (vk::SystemError& e) {
  5954. std::cerr << "ggml_vulkan: Failed to allocate pinned memory." << std::endl;
  5955. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  5956. // fallback to cpu buffer
  5957. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  5958. }
  5959. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  5960. buffer->buft = buft;
  5961. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  5962. return buffer;
  5963. UNUSED(buft);
  5964. }
  5965. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  5966. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  5967. UNUSED(buft);
  5968. }
  5969. // Should be changed to return device-specific host buffer type
  5970. // but that probably requires changes in llama.cpp
  5971. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  5972. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  5973. /* .iface = */ {
  5974. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  5975. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  5976. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  5977. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  5978. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  5979. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  5980. },
  5981. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  5982. /* .context = */ nullptr,
  5983. };
  5984. // Make sure device 0 is initialized
  5985. ggml_vk_instance_init();
  5986. ggml_vk_get_device(0);
  5987. return &ggml_backend_vk_buffer_type_host;
  5988. }
  5989. // backend
  5990. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  5991. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  5992. return ctx->name.c_str();
  5993. }
  5994. static void ggml_backend_vk_free(ggml_backend_t backend) {
  5995. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  5996. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  5997. ggml_vk_cleanup(ctx);
  5998. delete ctx;
  5999. delete backend;
  6000. }
  6001. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  6002. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6003. return &ctx->device->buffer_type;
  6004. }
  6005. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  6006. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  6007. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6008. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  6009. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6010. vk_context transfer_ctx;
  6011. if (ctx->transfer_ctx.expired()) {
  6012. // Initialize new transfer context
  6013. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6014. ctx->transfer_ctx = transfer_ctx;
  6015. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6016. } else {
  6017. transfer_ctx = ctx->transfer_ctx.lock();
  6018. }
  6019. vk_buffer buf = buf_ctx->dev_buffer;
  6020. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6021. }
  6022. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  6023. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  6024. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6025. GGML_ASSERT((tensor->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || tensor->buffer->buft == ggml_backend_vk_host_buffer_type()) && "unsupported buffer type");
  6026. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6027. vk_context transfer_ctx;
  6028. if (ctx->transfer_ctx.expired()) {
  6029. // Initialize new transfer context
  6030. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6031. ctx->transfer_ctx = transfer_ctx;
  6032. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6033. } else {
  6034. transfer_ctx = ctx->transfer_ctx.lock();
  6035. }
  6036. vk_buffer buf = buf_ctx->dev_buffer;
  6037. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6038. }
  6039. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  6040. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  6041. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6042. if ((dst->buffer->buft == ggml_backend_vk_get_default_buffer_type(backend) || dst->buffer->buft == ggml_backend_vk_host_buffer_type()) && ggml_backend_buffer_is_vk(src->buffer)) {
  6043. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  6044. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6045. vk_context transfer_ctx;
  6046. if (ctx->transfer_ctx.expired()) {
  6047. // Initialize new transfer context
  6048. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6049. ctx->transfer_ctx = transfer_ctx;
  6050. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6051. } else {
  6052. transfer_ctx = ctx->transfer_ctx.lock();
  6053. }
  6054. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  6055. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  6056. ggml_vk_buffer_copy_async(transfer_ctx, dst_buf, vk_tensor_offset(dst) + dst->view_offs, src_buf, vk_tensor_offset(src) + src->view_offs, ggml_nbytes(src));
  6057. return true;
  6058. }
  6059. return false;
  6060. }
  6061. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  6062. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  6063. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6064. if(ctx->transfer_ctx.expired()) {
  6065. return;
  6066. }
  6067. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  6068. ggml_vk_ctx_end(transfer_ctx);
  6069. for (auto& cpy : transfer_ctx->in_memcpys) {
  6070. memcpy(cpy.dst, cpy.src, cpy.n);
  6071. }
  6072. ggml_vk_submit(transfer_ctx, ctx->fence);
  6073. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_backend_vk_synchronize waitForFences");
  6074. ctx->device->device.resetFences({ ctx->fence });
  6075. for (auto& cpy : transfer_ctx->out_memcpys) {
  6076. memcpy(cpy.dst, cpy.src, cpy.n);
  6077. }
  6078. ctx->transfer_ctx.reset();
  6079. }
  6080. static bool ggml_vk_is_empty(ggml_tensor * node) {
  6081. return ggml_is_empty(node) || node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE;
  6082. }
  6083. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  6084. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  6085. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6086. for (int i = 0; i < cgraph->n_nodes; i++) {
  6087. ggml_vk_build_graph(ctx, cgraph->nodes[i], i, nullptr, 0, true, false, false);
  6088. }
  6089. ggml_vk_preallocate_buffers(ctx);
  6090. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  6091. int last_node = cgraph->n_nodes - 1;
  6092. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  6093. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  6094. last_node -= 1;
  6095. }
  6096. // Reserve tensor context space for all nodes
  6097. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  6098. bool first_node_in_batch = true; // true if next node will be first node in a batch
  6099. int submit_node_idx = 0; // index to first node in a batch
  6100. // Submit work every nodes_per_submit nodes to overlap CPU cmdbuffer generation with GPU execution.
  6101. // Start with a smaller count to get work submitted right away, and increase it after each submit.
  6102. int nodes_per_submit = 20;
  6103. int submitted_nodes = 0;
  6104. int submit_count = 0;
  6105. for (int i = 0; i < cgraph->n_nodes; i++) {
  6106. if (first_node_in_batch) {
  6107. submit_node_idx = i;
  6108. }
  6109. bool submit = (submitted_nodes >= nodes_per_submit) || (i == last_node);
  6110. bool enqueued = ggml_vk_build_graph(ctx, cgraph->nodes[i], i, cgraph->nodes[submit_node_idx], submit_node_idx, false, i == last_node, submit);
  6111. if (enqueued) {
  6112. ++submitted_nodes;
  6113. #ifndef GGML_VULKAN_CHECK_RESULTS
  6114. if (first_node_in_batch) {
  6115. first_node_in_batch = false;
  6116. }
  6117. #endif
  6118. }
  6119. if (submit) {
  6120. first_node_in_batch = true;
  6121. submitted_nodes = 0;
  6122. switch (submit_count) {
  6123. case 0:
  6124. nodes_per_submit = 50;
  6125. break;
  6126. default:
  6127. nodes_per_submit = 100;
  6128. break;
  6129. }
  6130. submit_count++;
  6131. }
  6132. }
  6133. #ifdef GGML_VULKAN_PERF
  6134. ctx->device->perf_logger->print_timings();
  6135. #endif
  6136. ggml_vk_graph_cleanup(ctx);
  6137. return GGML_STATUS_SUCCESS;
  6138. UNUSED(backend);
  6139. }
  6140. // TODO: enable async and synchronize
  6141. static ggml_backend_i ggml_backend_vk_interface = {
  6142. /* .get_name = */ ggml_backend_vk_name,
  6143. /* .free = */ ggml_backend_vk_free,
  6144. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  6145. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  6146. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  6147. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  6148. /* .graph_plan_create = */ NULL,
  6149. /* .graph_plan_free = */ NULL,
  6150. /* .graph_plan_update = */ NULL,
  6151. /* .graph_plan_compute = */ NULL,
  6152. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  6153. /* .event_record = */ NULL,
  6154. /* .event_wait = */ NULL,
  6155. };
  6156. static ggml_guid_t ggml_backend_vk_guid() {
  6157. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  6158. return &guid;
  6159. }
  6160. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  6161. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  6162. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  6163. ggml_vk_init(ctx, dev_num);
  6164. ggml_backend_t vk_backend = new ggml_backend {
  6165. /* .guid = */ ggml_backend_vk_guid(),
  6166. /* .interface = */ ggml_backend_vk_interface,
  6167. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  6168. /* .context = */ ctx,
  6169. };
  6170. return vk_backend;
  6171. }
  6172. bool ggml_backend_is_vk(ggml_backend_t backend) {
  6173. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  6174. }
  6175. int ggml_backend_vk_get_device_count() {
  6176. return ggml_vk_get_device_count();
  6177. }
  6178. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  6179. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  6180. int dev_idx = vk_instance.device_indices[device];
  6181. ggml_vk_get_device_description(dev_idx, description, description_size);
  6182. }
  6183. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  6184. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  6185. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  6186. vk::PhysicalDeviceMemoryProperties memprops = vkdev.getMemoryProperties();
  6187. for (const vk::MemoryHeap& heap : memprops.memoryHeaps) {
  6188. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  6189. *total = heap.size;
  6190. *free = heap.size;
  6191. break;
  6192. }
  6193. }
  6194. }
  6195. //////////////////////////
  6196. struct ggml_backend_vk_device_context {
  6197. size_t device;
  6198. std::string name;
  6199. std::string description;
  6200. };
  6201. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  6202. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6203. return ctx->name.c_str();
  6204. }
  6205. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  6206. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6207. return ctx->description.c_str();
  6208. }
  6209. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  6210. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  6211. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  6212. }
  6213. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  6214. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6215. return ggml_backend_vk_buffer_type(ctx->device);
  6216. }
  6217. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  6218. UNUSED(dev);
  6219. return ggml_backend_vk_host_buffer_type();
  6220. }
  6221. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  6222. UNUSED(dev);
  6223. return GGML_BACKEND_DEVICE_TYPE_GPU;
  6224. }
  6225. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  6226. props->name = ggml_backend_vk_device_get_name(dev);
  6227. props->description = ggml_backend_vk_device_get_description(dev);
  6228. props->type = ggml_backend_vk_device_get_type(dev);
  6229. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  6230. props->caps = {
  6231. /* .async = */ false,
  6232. /* .host_buffer = */ true,
  6233. /* .buffer_from_host_ptr = */ false,
  6234. /* .events = */ false,
  6235. };
  6236. }
  6237. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  6238. UNUSED(params);
  6239. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6240. return ggml_backend_vk_init(ctx->device);
  6241. }
  6242. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  6243. switch (op->op) {
  6244. case GGML_OP_UNARY:
  6245. switch (ggml_get_unary_op(op)) {
  6246. case GGML_UNARY_OP_GELU:
  6247. case GGML_UNARY_OP_GELU_QUICK:
  6248. case GGML_UNARY_OP_SILU:
  6249. case GGML_UNARY_OP_RELU:
  6250. case GGML_UNARY_OP_TANH:
  6251. return ggml_is_contiguous(op->src[0]);
  6252. default:
  6253. return false;
  6254. }
  6255. break;
  6256. case GGML_OP_MUL_MAT:
  6257. case GGML_OP_MUL_MAT_ID:
  6258. {
  6259. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6260. const vk_device& device = ggml_vk_get_device(ctx->device);
  6261. if (op->op == GGML_OP_MUL_MAT_ID && !device->mul_mat_id_s && !device->mul_mat_id_m && !device->mul_mat_id_l) {
  6262. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  6263. return false;
  6264. }
  6265. switch (op->src[0]->type) {
  6266. case GGML_TYPE_F32:
  6267. case GGML_TYPE_F16:
  6268. case GGML_TYPE_Q4_0:
  6269. case GGML_TYPE_Q4_1:
  6270. case GGML_TYPE_Q5_0:
  6271. case GGML_TYPE_Q5_1:
  6272. case GGML_TYPE_Q8_0:
  6273. case GGML_TYPE_Q2_K:
  6274. case GGML_TYPE_Q3_K:
  6275. case GGML_TYPE_Q4_K:
  6276. case GGML_TYPE_Q5_K:
  6277. case GGML_TYPE_Q6_K:
  6278. case GGML_TYPE_IQ4_NL:
  6279. break;
  6280. default:
  6281. return false;
  6282. }
  6283. struct ggml_tensor * a;
  6284. struct ggml_tensor * b;
  6285. if (op->op == GGML_OP_MUL_MAT) {
  6286. a = op->src[0];
  6287. b = op->src[1];
  6288. } else {
  6289. a = op->src[2];
  6290. b = op->src[1];
  6291. }
  6292. if (a->ne[3] != b->ne[3]) {
  6293. return false;
  6294. }
  6295. if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) ||
  6296. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  6297. return false;
  6298. }
  6299. return true;
  6300. } break;
  6301. case GGML_OP_FLASH_ATTN_EXT:
  6302. {
  6303. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6304. if (!ggml_vk_get_device(ctx->device)->coopmat2) {
  6305. return false;
  6306. }
  6307. switch (op->src[0]->ne[0]) {
  6308. case 64:
  6309. case 80:
  6310. case 96:
  6311. case 112:
  6312. case 128:
  6313. case 256:
  6314. break;
  6315. default:
  6316. return false;
  6317. }
  6318. if (op->src[0]->type != GGML_TYPE_F32) {
  6319. return false;
  6320. }
  6321. if (op->type != GGML_TYPE_F32) {
  6322. return false;
  6323. }
  6324. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  6325. return false;
  6326. }
  6327. // It's straightforward to support different K/V dequant, but would
  6328. // significantly increase the number of pipelines
  6329. if (op->src[1]->type != op->src[2]->type) {
  6330. return false;
  6331. }
  6332. switch (op->src[1]->type) {
  6333. case GGML_TYPE_F16:
  6334. case GGML_TYPE_Q4_0:
  6335. case GGML_TYPE_Q4_1:
  6336. case GGML_TYPE_Q5_0:
  6337. case GGML_TYPE_Q5_1:
  6338. case GGML_TYPE_Q8_0:
  6339. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  6340. //case GGML_TYPE_Q2_K:
  6341. //case GGML_TYPE_Q3_K:
  6342. //case GGML_TYPE_Q4_K:
  6343. //case GGML_TYPE_Q5_K:
  6344. //case GGML_TYPE_Q6_K:
  6345. case GGML_TYPE_IQ4_NL:
  6346. break;
  6347. default:
  6348. return false;
  6349. }
  6350. return true;
  6351. }
  6352. case GGML_OP_GET_ROWS:
  6353. {
  6354. switch (op->src[0]->type) {
  6355. case GGML_TYPE_F32:
  6356. case GGML_TYPE_F16:
  6357. case GGML_TYPE_Q4_0:
  6358. case GGML_TYPE_Q4_1:
  6359. case GGML_TYPE_Q5_0:
  6360. case GGML_TYPE_Q5_1:
  6361. case GGML_TYPE_Q8_0:
  6362. case GGML_TYPE_IQ4_NL:
  6363. return true;
  6364. default:
  6365. return false;
  6366. }
  6367. } break;
  6368. case GGML_OP_CONT:
  6369. case GGML_OP_CPY:
  6370. case GGML_OP_DUP:
  6371. {
  6372. ggml_type src0_type = op->src[0]->type;
  6373. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  6374. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  6375. return true;
  6376. }
  6377. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  6378. return true;
  6379. }
  6380. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  6381. return true;
  6382. }
  6383. return false;
  6384. } break;
  6385. case GGML_OP_REPEAT:
  6386. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  6387. case GGML_OP_ROPE:
  6388. return ggml_is_contiguous(op->src[0]);
  6389. case GGML_OP_NONE:
  6390. case GGML_OP_RESHAPE:
  6391. case GGML_OP_VIEW:
  6392. case GGML_OP_PERMUTE:
  6393. case GGML_OP_TRANSPOSE:
  6394. case GGML_OP_NORM:
  6395. case GGML_OP_GROUP_NORM:
  6396. case GGML_OP_RMS_NORM:
  6397. case GGML_OP_ADD:
  6398. case GGML_OP_ACC:
  6399. case GGML_OP_MUL:
  6400. case GGML_OP_DIV:
  6401. case GGML_OP_CONCAT:
  6402. case GGML_OP_UPSCALE:
  6403. case GGML_OP_SCALE:
  6404. case GGML_OP_SQR:
  6405. case GGML_OP_SIN:
  6406. case GGML_OP_COS:
  6407. case GGML_OP_CLAMP:
  6408. case GGML_OP_PAD:
  6409. case GGML_OP_DIAG_MASK_INF:
  6410. case GGML_OP_SOFT_MAX:
  6411. case GGML_OP_ARGSORT:
  6412. case GGML_OP_SUM_ROWS:
  6413. case GGML_OP_IM2COL:
  6414. case GGML_OP_TIMESTEP_EMBEDDING:
  6415. case GGML_OP_POOL_2D:
  6416. case GGML_OP_LEAKY_RELU:
  6417. return true;
  6418. default:
  6419. return false;
  6420. }
  6421. UNUSED(dev);
  6422. }
  6423. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  6424. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  6425. return false;
  6426. }
  6427. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6428. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  6429. return buft_ctx->device->idx == ctx->device;
  6430. }
  6431. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  6432. const int min_batch_size = 32;
  6433. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  6434. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  6435. UNUSED(dev);
  6436. }
  6437. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  6438. /* .get_name = */ ggml_backend_vk_device_get_name,
  6439. /* .get_description = */ ggml_backend_vk_device_get_description,
  6440. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  6441. /* .get_type = */ ggml_backend_vk_device_get_type,
  6442. /* .get_props = */ ggml_backend_vk_device_get_props,
  6443. /* .init_backend = */ ggml_backend_vk_device_init,
  6444. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  6445. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  6446. /* .buffer_from_host_ptr = */ NULL,
  6447. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  6448. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  6449. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  6450. /* .event_new = */ NULL,
  6451. /* .event_free = */ NULL,
  6452. /* .event_synchronize = */ NULL,
  6453. };
  6454. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  6455. UNUSED(reg);
  6456. return GGML_VK_NAME;
  6457. }
  6458. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  6459. UNUSED(reg);
  6460. return ggml_backend_vk_get_device_count();
  6461. }
  6462. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  6463. static std::vector<ggml_backend_dev_t> devices;
  6464. static bool initialized = false;
  6465. {
  6466. static std::mutex mutex;
  6467. std::lock_guard<std::mutex> lock(mutex);
  6468. if (!initialized) {
  6469. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  6470. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  6471. char desc[256];
  6472. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  6473. ctx->device = i;
  6474. ctx->name = GGML_VK_NAME + std::to_string(i);
  6475. ctx->description = desc;
  6476. devices.push_back(new ggml_backend_device {
  6477. /* .iface = */ ggml_backend_vk_device_i,
  6478. /* .reg = */ reg,
  6479. /* .context = */ ctx,
  6480. });
  6481. }
  6482. initialized = true;
  6483. }
  6484. }
  6485. GGML_ASSERT(device < devices.size());
  6486. return devices[device];
  6487. }
  6488. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  6489. /* .get_name = */ ggml_backend_vk_reg_get_name,
  6490. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  6491. /* .get_device = */ ggml_backend_vk_reg_get_device,
  6492. /* .get_proc_address = */ NULL,
  6493. };
  6494. ggml_backend_reg_t ggml_backend_vk_reg() {
  6495. static ggml_backend_reg reg = {
  6496. /* .api_version = */ GGML_BACKEND_API_VERSION,
  6497. /* .iface = */ ggml_backend_vk_reg_i,
  6498. /* .context = */ nullptr,
  6499. };
  6500. return &reg;
  6501. }
  6502. // Extension availability
  6503. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  6504. #ifdef GGML_VULKAN_VALIDATE
  6505. bool portability_enumeration_ext = false;
  6506. // Check for portability enumeration extension for MoltenVK support
  6507. for (const auto& properties : instance_extensions) {
  6508. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  6509. return true;
  6510. }
  6511. }
  6512. if (!portability_enumeration_ext) {
  6513. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  6514. }
  6515. #endif
  6516. return false;
  6517. UNUSED(instance_extensions);
  6518. }
  6519. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  6520. #ifdef __APPLE__
  6521. bool portability_enumeration_ext = false;
  6522. // Check for portability enumeration extension for MoltenVK support
  6523. for (const auto& properties : instance_extensions) {
  6524. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  6525. return true;
  6526. }
  6527. }
  6528. if (!portability_enumeration_ext) {
  6529. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  6530. }
  6531. #endif
  6532. return false;
  6533. UNUSED(instance_extensions);
  6534. }
  6535. // checks
  6536. #ifdef GGML_VULKAN_CHECK_RESULTS
  6537. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  6538. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  6539. return;
  6540. }
  6541. for (int j = 0; j < level; j++) {
  6542. std::cerr << " ";
  6543. }
  6544. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  6545. done.push_back(tensor);
  6546. for (int i = 0; i < GGML_MAX_SRC; i++) {
  6547. if (tensor->src[i] != nullptr) {
  6548. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  6549. }
  6550. }
  6551. }
  6552. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  6553. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  6554. return;
  6555. }
  6556. i0 = std::max(i0, 5);
  6557. i1 = std::max(i1, 5);
  6558. i2 = std::max(i2, 0);
  6559. i3 = std::max(i3, 0);
  6560. fprintf(stderr, " ");
  6561. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  6562. fprintf(stderr, "%7d ", idx1);
  6563. }
  6564. fprintf(stderr, "\n");
  6565. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  6566. fprintf(stderr, "%7d: ", idx0);
  6567. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  6568. 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]) {
  6569. float val;
  6570. if (tensor->type == GGML_TYPE_F32) {
  6571. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  6572. } else if (tensor->type == GGML_TYPE_F16) {
  6573. 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]));
  6574. } else if (tensor->type == GGML_TYPE_I32) {
  6575. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  6576. } else {
  6577. GGML_ABORT("fatal error");
  6578. }
  6579. fprintf(stderr, "% 7.2f ", val);
  6580. } else {
  6581. fprintf(stderr, " ");
  6582. }
  6583. }
  6584. fprintf(stderr, "\n");
  6585. }
  6586. }
  6587. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  6588. void * tensor_data = tensor->data;
  6589. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  6590. if (is_gpu) {
  6591. const size_t tensor_size = ggml_nbytes(tensor);
  6592. tensor_data = malloc(tensor_size);
  6593. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6594. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  6595. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  6596. }
  6597. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  6598. std::cerr << "tensor=" << tensor << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << std::endl;
  6599. if (tensor->src[0] != nullptr) {
  6600. std::cerr << "tensor->src[0]=" << tensor->src[0] << " name=" << tensor->src[0]->name << " op=" << ggml_op_name(tensor->src[0]->op) << " type=" << ggml_type_name(tensor->src[0]->type) << " ne0=" << tensor->src[0]->ne[0] << " nb0=" << tensor->src[0]->nb[0] << " ne1=" << tensor->src[0]->ne[1] << " nb1=" << tensor->src[0]->nb[1] << " ne2=" << tensor->src[0]->ne[2] << " nb2=" << tensor->src[0]->nb[2] << " ne3=" << tensor->src[0]->ne[3] << " nb3=" << tensor->src[0]->nb[3] << std::endl;
  6601. }
  6602. if (tensor->src[1] != nullptr) {
  6603. std::cerr << "tensor->src[1]=" << tensor->src[1] << " name=" << tensor->src[1]->name << " op=" << ggml_op_name(tensor->src[1]->op) << " type=" << ggml_type_name(tensor->src[1]->type) << " ne0=" << tensor->src[1]->ne[0] << " nb0=" << tensor->src[1]->nb[0] << " ne1=" << tensor->src[1]->ne[1] << " nb1=" << tensor->src[1]->nb[1] << " ne2=" << tensor->src[1]->ne[2] << " nb2=" << tensor->src[1]->nb[2] << " ne3=" << tensor->src[1]->ne[3] << " nb3=" << tensor->src[1]->nb[3] << std::endl;
  6604. }
  6605. std::cerr << std::endl << "Result:" << std::endl;
  6606. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  6607. std::cerr << std::endl;
  6608. std::vector<const ggml_tensor *> done;
  6609. ggml_vk_print_graph_origin(tensor, done);
  6610. if (is_gpu) {
  6611. free(tensor_data);
  6612. }
  6613. }
  6614. void * comp_result;
  6615. size_t comp_size;
  6616. size_t comp_nb[GGML_MAX_DIMS];
  6617. size_t check_counter = 0;
  6618. static void ggml_vk_check_results_0(ggml_tensor * tensor) {
  6619. if (tensor->op == GGML_OP_TRANSPOSE) {
  6620. return;
  6621. }
  6622. check_counter++;
  6623. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  6624. return;
  6625. }
  6626. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  6627. ggml_tensor * src0 = tensor->src[0];
  6628. ggml_tensor * src1 = tensor->src[1];
  6629. ggml_tensor * src2 = tensor->src[2];
  6630. ggml_tensor * src3 = tensor->src[3];
  6631. struct ggml_init_params iparams = {
  6632. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  6633. /*.mem_buffer =*/ NULL,
  6634. /*.no_alloc =*/ false,
  6635. };
  6636. struct ggml_context * ggml_ctx = ggml_init(iparams);
  6637. struct ggml_tensor * src0_clone = nullptr;
  6638. struct ggml_tensor * src1_clone = nullptr;
  6639. struct ggml_tensor * src2_clone = nullptr;
  6640. struct ggml_tensor * src3_clone = nullptr;
  6641. struct ggml_tensor * tensor_clone = nullptr;
  6642. size_t src0_size;
  6643. size_t src1_size;
  6644. size_t src2_size;
  6645. size_t src3_size;
  6646. void * src0_buffer = nullptr;
  6647. void * src1_buffer = nullptr;
  6648. void * src2_buffer = nullptr;
  6649. void * src3_buffer = nullptr;
  6650. if (src0 != nullptr) {
  6651. src0_clone = ggml_dup_tensor(ggml_ctx, src0);
  6652. src0_size = ggml_nbytes(src0);
  6653. src0_buffer = malloc(src0_size);
  6654. src0_clone->data = src0_buffer;
  6655. if (ggml_backend_buffer_is_host(src0->buffer)) {
  6656. memcpy(src0_clone->data, src0->data, src0_size);
  6657. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6658. } else if (ggml_backend_buffer_is_vk(src0->buffer)) {
  6659. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6660. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6661. uint64_t offset = vk_tensor_offset(src0) + src0->view_offs;
  6662. if (!ggml_is_contiguous(src0) && ggml_vk_dim01_contiguous(src0)) {
  6663. for (int i3 = 0; i3 < src0->ne[3]; i3++) {
  6664. for (int i2 = 0; i2 < src0->ne[2]; i2++) {
  6665. const int idx = i3*src0->ne[2] + i2;
  6666. ggml_vk_buffer_read(buffer_gpu, offset + idx * src0->nb[2], ((char *)src0_clone->data + idx * src0_clone->nb[2]), src0->ne[1] * src0->nb[1]);
  6667. }
  6668. }
  6669. src0_clone->nb[0] = src0->nb[0];
  6670. src0_clone->nb[1] = src0->nb[1];
  6671. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  6672. src0_clone->nb[i] = src0_clone->nb[i - 1]*src0_clone->ne[i - 1];
  6673. }
  6674. } else {
  6675. if (offset + src0_size >= buffer_gpu->size) {
  6676. src0_size = buffer_gpu->size - offset;
  6677. }
  6678. ggml_vk_buffer_read(buffer_gpu, offset, src0_clone->data, src0_size);
  6679. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6680. }
  6681. } else {
  6682. GGML_ABORT("fatal error");
  6683. }
  6684. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6685. ggml_vk_print_tensor(src0, "src0");
  6686. }
  6687. }
  6688. if (src1 != nullptr) {
  6689. src1_clone = ggml_dup_tensor(ggml_ctx, src1);
  6690. src1_size = ggml_nbytes(src1);
  6691. src1_buffer = malloc(src1_size);
  6692. src1_clone->data = src1_buffer;
  6693. if (ggml_backend_buffer_is_host(src1->buffer)) {
  6694. memcpy(src1_clone->data, src1->data, src1_size);
  6695. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6696. } else if (ggml_backend_buffer_is_vk(src1->buffer)) {
  6697. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6698. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6699. uint64_t offset = vk_tensor_offset(src1) + src1->view_offs;
  6700. if (!ggml_is_contiguous(src1) && ggml_vk_dim01_contiguous(src1)) {
  6701. for (int i3 = 0; i3 < src1->ne[3]; i3++) {
  6702. for (int i2 = 0; i2 < src1->ne[2]; i2++) {
  6703. const int idx = i3*src1->ne[2] + i2;
  6704. ggml_vk_buffer_read(buffer_gpu, offset + idx * src1->nb[2], ((char *)src1_clone->data + idx * src1_clone->nb[2]), src1->ne[1] * src1->nb[1]);
  6705. }
  6706. }
  6707. src1_clone->nb[0] = src1->nb[0];
  6708. src1_clone->nb[1] = src1->nb[1];
  6709. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  6710. src1_clone->nb[i] = src1_clone->nb[i - 1]*src1_clone->ne[i - 1];
  6711. }
  6712. } else {
  6713. if (offset + src1_size >= buffer_gpu->size) {
  6714. src1_size = buffer_gpu->size - offset;
  6715. }
  6716. ggml_vk_buffer_read(buffer_gpu, offset, src1_clone->data, src1_size);
  6717. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6718. }
  6719. } else {
  6720. GGML_ABORT("fatal error");
  6721. }
  6722. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6723. ggml_vk_print_tensor(src1, "src1");
  6724. }
  6725. }
  6726. if (src2 != nullptr) {
  6727. src2_clone = ggml_dup_tensor(ggml_ctx, src2);
  6728. src2_size = ggml_nbytes(src2);
  6729. src2_buffer = malloc(src2_size);
  6730. src2_clone->data = src2_buffer;
  6731. if (ggml_backend_buffer_is_host(src2->buffer)) {
  6732. memcpy(src2_clone->data, src2->data, src2_size);
  6733. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6734. } else if (ggml_backend_buffer_is_vk(src2->buffer)) {
  6735. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src2->buffer->context;
  6736. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6737. uint64_t offset = vk_tensor_offset(src2) + src2->view_offs;
  6738. if (!ggml_is_contiguous(src2) && ggml_vk_dim01_contiguous(src2)) {
  6739. for (int i3 = 0; i3 < src2->ne[3]; i3++) {
  6740. for (int i2 = 0; i2 < src2->ne[2]; i2++) {
  6741. const int idx = i3*src2->ne[2] + i2;
  6742. ggml_vk_buffer_read(buffer_gpu, offset + idx * src2->nb[2], ((char *)src2_clone->data + idx * src2_clone->nb[2]), src2->ne[1] * src2->nb[1]);
  6743. }
  6744. }
  6745. src2_clone->nb[0] = src2->nb[0];
  6746. src2_clone->nb[1] = src2->nb[1];
  6747. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  6748. src2_clone->nb[i] = src2_clone->nb[i - 1]*src2_clone->ne[i - 1];
  6749. }
  6750. } else {
  6751. if (offset + src2_size >= buffer_gpu->size) {
  6752. src2_size = buffer_gpu->size - offset;
  6753. }
  6754. ggml_vk_buffer_read(buffer_gpu, offset, src2_clone->data, src2_size);
  6755. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6756. }
  6757. } else {
  6758. GGML_ABORT("fatal error");
  6759. }
  6760. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6761. ggml_vk_print_tensor(src2, "src2");
  6762. }
  6763. }
  6764. if (src3 != nullptr) {
  6765. src3_clone = ggml_dup_tensor(ggml_ctx, src3);
  6766. src3_size = ggml_nbytes(src3);
  6767. src3_buffer = malloc(src3_size);
  6768. src3_clone->data = src3_buffer;
  6769. if (ggml_backend_buffer_is_host(src3->buffer)) {
  6770. memcpy(src3_clone->data, src3->data, src3_size);
  6771. memcpy(src3_clone->nb, src3->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6772. } else if (ggml_backend_buffer_is_vk(src3->buffer)) {
  6773. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src3->buffer->context;
  6774. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6775. uint64_t offset = vk_tensor_offset(src3) + src3->view_offs;
  6776. if (!ggml_is_contiguous(src3) && ggml_vk_dim01_contiguous(src3)) {
  6777. for (int i3 = 0; i3 < src3->ne[3]; i3++) {
  6778. for (int i2 = 0; i2 < src3->ne[2]; i2++) {
  6779. const int idx = i3*src3->ne[2] + i2;
  6780. ggml_vk_buffer_read(buffer_gpu, offset + idx * src3->nb[2], ((char *)src3_clone->data + idx * src3_clone->nb[2]), src3->ne[1] * src3->nb[1]);
  6781. }
  6782. }
  6783. src3_clone->nb[0] = src3->nb[0];
  6784. src3_clone->nb[1] = src3->nb[1];
  6785. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  6786. src3_clone->nb[i] = src3_clone->nb[i - 1]*src3_clone->ne[i - 1];
  6787. }
  6788. } else {
  6789. if (offset + src3_size >= buffer_gpu->size) {
  6790. src3_size = buffer_gpu->size - offset;
  6791. }
  6792. ggml_vk_buffer_read(buffer_gpu, offset, src3_clone->data, src3_size);
  6793. memcpy(src3_clone->nb, src3->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6794. }
  6795. } else {
  6796. GGML_ABORT("fatal error");
  6797. }
  6798. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6799. ggml_vk_print_tensor(src3, "src3");
  6800. }
  6801. }
  6802. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  6803. const float *params = (const float *)tensor->op_params;
  6804. tensor_clone = ggml_flash_attn_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, src3_clone, params[0], params[1], params[2]);
  6805. } else if (tensor->op == GGML_OP_MUL_MAT) {
  6806. tensor_clone = ggml_mul_mat(ggml_ctx, src0_clone, src1_clone);
  6807. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  6808. tensor_clone = ggml_mul_mat_id(ggml_ctx, src0_clone, src1_clone, src2_clone);
  6809. } else if (tensor->op == GGML_OP_MUL) {
  6810. tensor_clone = ggml_mul(ggml_ctx, src0_clone, src1_clone);
  6811. } else if (tensor->op == GGML_OP_DIV) {
  6812. tensor_clone = ggml_div(ggml_ctx, src0_clone, src1_clone);
  6813. } else if (tensor->op == GGML_OP_CONCAT) {
  6814. tensor_clone = ggml_concat(ggml_ctx, src0_clone, src1_clone, *(int *)tensor->op_params);
  6815. } else if (tensor->op == GGML_OP_UPSCALE) {
  6816. tensor_clone = ggml_upscale_ext(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  6817. } else if (tensor->op == GGML_OP_SCALE) {
  6818. tensor_clone = ggml_scale(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0]);
  6819. } else if (tensor->op == GGML_OP_SQR) {
  6820. tensor_clone = ggml_sqr(ggml_ctx, src0_clone);
  6821. } else if (tensor->op == GGML_OP_SIN) {
  6822. tensor_clone = ggml_sin(ggml_ctx, src0_clone);
  6823. } else if (tensor->op == GGML_OP_COS) {
  6824. tensor_clone = ggml_cos(ggml_ctx, src0_clone);
  6825. } else if (tensor->op == GGML_OP_CLAMP) {
  6826. tensor_clone = ggml_clamp(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  6827. } else if (tensor->op == GGML_OP_PAD) {
  6828. tensor_clone = ggml_pad(ggml_ctx, src0_clone, tensor->ne[0] - src0_clone->ne[0], tensor->ne[1] - src0_clone->ne[1], tensor->ne[2] - src0_clone->ne[2], tensor->ne[3] - src0_clone->ne[3]);
  6829. } else if (tensor->op == GGML_OP_REPEAT) {
  6830. tensor_clone = ggml_repeat(ggml_ctx, src0_clone, tensor);
  6831. } else if (tensor->op == GGML_OP_ADD) {
  6832. tensor_clone = ggml_add(ggml_ctx, src0_clone, src1_clone);
  6833. } else if (tensor->op == GGML_OP_ACC) {
  6834. tensor_clone = ggml_acc(ggml_ctx, src0_clone, src1_clone, tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3]);
  6835. } else if (tensor->op == GGML_OP_NORM) {
  6836. tensor_clone = ggml_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  6837. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  6838. tensor_clone = ggml_group_norm(ggml_ctx, src0_clone, *(int *)tensor->op_params, ((float *)tensor->op_params)[1]);
  6839. } else if (tensor->op == GGML_OP_RMS_NORM) {
  6840. tensor_clone = ggml_rms_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  6841. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  6842. if (src1 != nullptr) {
  6843. tensor_clone = ggml_soft_max_ext(ggml_ctx, src0_clone, src1_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  6844. } else {
  6845. tensor_clone = ggml_soft_max(ggml_ctx, src0_clone);
  6846. }
  6847. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  6848. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src0_clone, *(int *)tensor->op_params);
  6849. } else if (tensor->op == GGML_OP_ROPE) {
  6850. const int n_dims = ((int32_t *) tensor->op_params)[1];
  6851. const int mode = ((int32_t *) tensor->op_params)[2];
  6852. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  6853. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  6854. const float freq_base = ((float *) tensor->op_params)[5];
  6855. const float freq_scale = ((float *) tensor->op_params)[6];
  6856. const float ext_factor = ((float *) tensor->op_params)[7];
  6857. const float attn_factor = ((float *) tensor->op_params)[8];
  6858. const float beta_fast = ((float *) tensor->op_params)[9];
  6859. const float beta_slow = ((float *) tensor->op_params)[10];
  6860. tensor_clone = ggml_rope_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  6861. } else if (tensor->op == GGML_OP_UNARY) {
  6862. switch (ggml_get_unary_op(tensor)) {
  6863. case GGML_UNARY_OP_SILU:
  6864. tensor_clone = ggml_silu(ggml_ctx, src0_clone);
  6865. break;
  6866. case GGML_UNARY_OP_GELU:
  6867. tensor_clone = ggml_gelu(ggml_ctx, src0_clone);
  6868. break;
  6869. case GGML_UNARY_OP_GELU_QUICK:
  6870. tensor_clone = ggml_gelu_quick(ggml_ctx, src0_clone);
  6871. break;
  6872. case GGML_UNARY_OP_RELU:
  6873. tensor_clone = ggml_relu(ggml_ctx, src0_clone);
  6874. break;
  6875. case GGML_UNARY_OP_TANH:
  6876. tensor_clone = ggml_tanh(ggml_ctx, src0_clone);
  6877. break;
  6878. default:
  6879. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  6880. GGML_ABORT("fatal error");
  6881. }
  6882. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  6883. if (src1 == nullptr) {
  6884. tensor_clone = ggml_dup(ggml_ctx, src0_clone);
  6885. tensor_clone->type = tensor->type;
  6886. } else {
  6887. tensor_clone = ggml_cpy(ggml_ctx, src0_clone, src1_clone);
  6888. }
  6889. } else if (tensor->op == GGML_OP_CONT) {
  6890. tensor_clone = ggml_cont_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  6891. } else if (tensor->op == GGML_OP_RESHAPE) {
  6892. tensor_clone = ggml_reshape_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  6893. } else if (tensor->op == GGML_OP_VIEW) {
  6894. 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]);
  6895. } else if (tensor->op == GGML_OP_PERMUTE) {
  6896. int32_t * params = (int32_t *)tensor->op_params;
  6897. tensor_clone = ggml_permute(ggml_ctx, src0_clone, params[0], params[1], params[2], params[3]);
  6898. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  6899. tensor_clone = ggml_transpose(ggml_ctx, src0_clone);
  6900. } else if (tensor->op == GGML_OP_GET_ROWS) {
  6901. tensor_clone = ggml_get_rows(ggml_ctx, src0_clone, src1_clone);
  6902. } else if (tensor->op == GGML_OP_ARGSORT) {
  6903. tensor_clone = ggml_argsort(ggml_ctx, src0_clone, (ggml_sort_order) *(int *)tensor->op_params);
  6904. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  6905. tensor_clone = ggml_sum_rows(ggml_ctx, src0_clone);
  6906. } else if (tensor->op == GGML_OP_IM2COL) {
  6907. const int32_t s0 = tensor->op_params[0];
  6908. const int32_t s1 = tensor->op_params[1];
  6909. const int32_t p0 = tensor->op_params[2];
  6910. const int32_t p1 = tensor->op_params[3];
  6911. const int32_t d0 = tensor->op_params[4];
  6912. const int32_t d1 = tensor->op_params[5];
  6913. const bool is_2D = tensor->op_params[6] == 1;
  6914. tensor_clone = ggml_im2col(ggml_ctx, src0_clone, src1_clone, s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  6915. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  6916. const int32_t dim = tensor->op_params[0];
  6917. const int32_t max_period = tensor->op_params[1];
  6918. tensor_clone = ggml_timestep_embedding(ggml_ctx, src0_clone, dim, max_period);
  6919. } else if (tensor->op == GGML_OP_POOL_2D) {
  6920. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  6921. const int32_t k0 = tensor->op_params[1];
  6922. const int32_t k1 = tensor->op_params[2];
  6923. const int32_t s0 = tensor->op_params[3];
  6924. const int32_t s1 = tensor->op_params[4];
  6925. const int32_t p0 = tensor->op_params[5];
  6926. const int32_t p1 = tensor->op_params[6];
  6927. tensor_clone = ggml_pool_2d(ggml_ctx, src0_clone, op, k0, k1, s0, s1, p0, p1);
  6928. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  6929. const float * op_params = (const float *)tensor->op_params;
  6930. tensor_clone = ggml_leaky_relu(ggml_ctx, src0_clone, op_params[0], false);
  6931. } else {
  6932. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  6933. GGML_ABORT("fatal error");
  6934. }
  6935. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  6936. ggml_build_forward_expand(cgraph, tensor_clone);
  6937. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 8);
  6938. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  6939. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  6940. }
  6941. comp_size = ggml_nbytes(tensor_clone);
  6942. comp_result = malloc(comp_size);
  6943. memcpy(comp_result, tensor_clone->data, comp_size);
  6944. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  6945. if (src0 != nullptr) {
  6946. free(src0_buffer);
  6947. }
  6948. if (src1 != nullptr) {
  6949. free(src1_buffer);
  6950. }
  6951. ggml_free(ggml_ctx);
  6952. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  6953. }
  6954. static void ggml_vk_check_results_1(ggml_tensor * tensor) {
  6955. if (tensor->op == GGML_OP_TRANSPOSE) {
  6956. return;
  6957. }
  6958. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  6959. return;
  6960. }
  6961. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  6962. ggml_tensor * src0 = tensor->src[0];
  6963. ggml_tensor * src1 = tensor->src[1];
  6964. ggml_tensor * src2 = tensor->src[2];
  6965. void * tensor_data = tensor->data;
  6966. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  6967. size_t tensor_size = ggml_nbytes(tensor);
  6968. tensor_data = malloc(tensor_size);
  6969. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6970. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  6971. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  6972. if (offset + tensor_size >= buffer_gpu->size) {
  6973. tensor_size = buffer_gpu->size - offset;
  6974. }
  6975. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  6976. }
  6977. float first_error_result = -1.0f;
  6978. float first_error_correct = -1.0f;
  6979. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  6980. double avg_err = 0.0;
  6981. size_t counter = 0;
  6982. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  6983. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  6984. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  6985. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  6986. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  6987. float correct = 0.0f;
  6988. float result = 0.0f;
  6989. if (buffer_size_fit) {
  6990. if (tensor->type == GGML_TYPE_F32) {
  6991. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  6992. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  6993. } else if (tensor->type == GGML_TYPE_F16) {
  6994. 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]));
  6995. 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]));
  6996. } else if (tensor->type == GGML_TYPE_I32) {
  6997. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  6998. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  6999. } else {
  7000. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  7001. }
  7002. } else {
  7003. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  7004. GGML_ABORT("fatal error");
  7005. }
  7006. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  7007. 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;
  7008. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  7009. if (src0 != nullptr) {
  7010. std::cerr << "src0=" << src0 << " src0->name=" << src0->name << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  7011. }
  7012. if (src1 != nullptr) {
  7013. std::cerr << "src1=" << src1 << " src1->name=" << src1->name << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  7014. }
  7015. if (src2 != nullptr) {
  7016. std::cerr << "src2=" << src2 << " src2->name=" << src2->name << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  7017. }
  7018. 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;
  7019. std::cerr << std::endl << "Result:" << std::endl;
  7020. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  7021. std::cerr << std::endl << "Correct:" << std::endl;
  7022. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  7023. std::cerr << std::endl;
  7024. std::vector<const ggml_tensor *> done;
  7025. ggml_vk_print_graph_origin(tensor, done);
  7026. GGML_ABORT("fatal error");
  7027. }
  7028. if (first_error[0] == -1 && std::fabs(correct - result) > 0.1f) {
  7029. first_error[0] = i0;
  7030. first_error[1] = i1;
  7031. first_error[2] = i2;
  7032. first_error[3] = i3;
  7033. first_error_result = result;
  7034. first_error_correct = correct;
  7035. }
  7036. // Special case, value is infinite, avoid NaN result in avg_err
  7037. // NaN also appears in results, if both are nan error is 0
  7038. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  7039. avg_err += std::fabs(correct - result);
  7040. }
  7041. counter++;
  7042. }
  7043. }
  7044. }
  7045. }
  7046. avg_err /= counter;
  7047. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7048. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  7049. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  7050. if (src0 != nullptr) {
  7051. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  7052. }
  7053. if (src1 != nullptr) {
  7054. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  7055. }
  7056. if (src2 != nullptr) {
  7057. std::cerr << "src2=" << src2 << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  7058. }
  7059. 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;
  7060. std::cerr << std::endl << "Result:" << std::endl;
  7061. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  7062. std::cerr << std::endl << "Correct:" << std::endl;
  7063. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  7064. std::cerr << std::endl;
  7065. std::vector<const ggml_tensor *> done;
  7066. ggml_vk_print_graph_origin(tensor, done);
  7067. }
  7068. if (avg_err > 0.05 || std::isnan(avg_err)) {
  7069. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  7070. std::cerr << "tensor=" << tensor << " tensor->name=" << tensor->name << " tensor->type: " << ggml_type_name(tensor->type) << " ne0=" << tensor->ne[0] << " nb0=" << tensor->nb[0] << " ne1=" << tensor->ne[1] << " nb1=" << tensor->nb[1] << " ne2=" << tensor->ne[2] << " nb2=" << tensor->nb[2] << " ne3=" << tensor->ne[3] << " nb3=" << tensor->nb[3] << " offset=" << tensor->view_offs << std::endl;
  7071. if (src0 != nullptr) {
  7072. std::cerr << "src0=" << src0 << " op=" << ggml_op_name(src0->op) << " type=" << ggml_type_name(src0->type) << " ne0=" << src0->ne[0] << " nb0=" << src0->nb[0] << " ne1=" << src0->ne[1] << " nb1=" << src0->nb[1] << " ne2=" << src0->ne[2] << " nb2=" << src0->nb[2] << " ne3=" << src0->ne[3] << " nb3=" << src0->nb[3] << " offset=" << src0->view_offs << std::endl;
  7073. }
  7074. if (src1 != nullptr) {
  7075. std::cerr << "src1=" << src1 << " op=" << ggml_op_name(src1->op) << " type=" << ggml_type_name(src1->type) << " ne0=" << src1->ne[0] << " nb0=" << src1->nb[0] << " ne1=" << src1->ne[1] << " nb1=" << src1->nb[1] << " ne2=" << src1->ne[2] << " nb2=" << src1->nb[2] << " ne3=" << src1->ne[3] << " nb3=" << src1->nb[3] << " offset=" << src1->view_offs << std::endl;
  7076. }
  7077. if (src2 != nullptr) {
  7078. std::cerr << "src2=" << src2 << " op=" << ggml_op_name(src2->op) << " type=" << ggml_type_name(src2->type) << " ne0=" << src2->ne[0] << " nb0=" << src2->nb[0] << " ne1=" << src2->ne[1] << " nb1=" << src2->nb[1] << " ne2=" << src2->ne[2] << " nb2=" << src2->nb[2] << " ne3=" << src2->ne[3] << " nb3=" << src2->nb[3] << " offset=" << src2->view_offs << std::endl;
  7079. }
  7080. 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;
  7081. std::cerr << std::endl << "Result:" << std::endl;
  7082. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  7083. std::cerr << std::endl << "Correct:" << std::endl;
  7084. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  7085. std::cerr << std::endl;
  7086. std::vector<const ggml_tensor *> done;
  7087. ggml_vk_print_graph_origin(tensor, done);
  7088. GGML_ABORT("fatal error");
  7089. } else {
  7090. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  7091. }
  7092. free(comp_result);
  7093. comp_result = nullptr;
  7094. comp_size = 0;
  7095. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  7096. free(tensor_data);
  7097. }
  7098. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  7099. }
  7100. #endif
  7101. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)