ggml-vulkan.cpp 766 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. // We use VULKAN_HPP_DEFAULT_DISPATCHER, but not VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  10. // to avoid conflicts with applications or other libraries who might use it.
  11. #if VK_HEADER_VERSION >= 301
  12. namespace vk::detail { class DispatchLoaderDynamic; }
  13. using vk::detail::DispatchLoaderDynamic;
  14. #else
  15. namespace vk { class DispatchLoaderDynamic; }
  16. using vk::DispatchLoaderDynamic;
  17. #endif
  18. DispatchLoaderDynamic & ggml_vk_default_dispatcher();
  19. #define VULKAN_HPP_DEFAULT_DISPATCHER ggml_vk_default_dispatcher()
  20. #include <vulkan/vulkan.hpp>
  21. #include <algorithm>
  22. #include <cmath>
  23. #include <iomanip>
  24. #include <iostream>
  25. #include <tuple>
  26. #include <vector>
  27. #include <sstream>
  28. #include <utility>
  29. #include <memory>
  30. #include <limits>
  31. #include <map>
  32. #include <set>
  33. #include <unordered_map>
  34. #include <memory>
  35. #include <mutex>
  36. #include <future>
  37. #include <thread>
  38. #if defined(_MSC_VER)
  39. # define NOMINMAX 1
  40. # include <windows.h>
  41. # define YIELD() YieldProcessor()
  42. #elif defined(__clang__) || defined(__GNUC__)
  43. # if defined(__x86_64__) ||defined(__i386__)
  44. # include <immintrin.h>
  45. # define YIELD() _mm_pause()
  46. # elif defined(__arm__) || defined(__aarch64__)
  47. # if defined(__clang__)
  48. # include <arm_acle.h>
  49. # define YIELD() __yield()
  50. # else
  51. # define YIELD() asm volatile("yield")
  52. # endif
  53. # endif
  54. #endif
  55. #if !defined(YIELD)
  56. #define YIELD()
  57. #endif
  58. #include "ggml-impl.h"
  59. #include "ggml-backend-impl.h"
  60. #include "ggml-vulkan-shaders.hpp"
  61. // remove this once it's more widely available in the SDK
  62. #if !defined(VK_KHR_shader_bfloat16)
  63. #define VK_KHR_shader_bfloat16 1
  64. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  65. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  66. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  67. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  68. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  69. VkStructureType sType;
  70. void* pNext;
  71. VkBool32 shaderBFloat16Type;
  72. VkBool32 shaderBFloat16DotProduct;
  73. VkBool32 shaderBFloat16CooperativeMatrix;
  74. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  75. #endif
  76. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  77. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  78. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  79. #define VK_VENDOR_ID_AMD 0x1002
  80. #define VK_VENDOR_ID_APPLE 0x106b
  81. #define VK_VENDOR_ID_INTEL 0x8086
  82. #define VK_VENDOR_ID_NVIDIA 0x10de
  83. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  84. #define GGML_VK_MAX_NODES 8192
  85. #define VK_CHECK(err, msg) \
  86. do { \
  87. vk::Result err_ = (err); \
  88. if (err_ != vk::Result::eSuccess) { \
  89. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  90. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  91. exit(1); \
  92. } \
  93. } while (0)
  94. #ifdef GGML_VULKAN_DEBUG
  95. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  96. #else
  97. #define VK_LOG_DEBUG(msg) ((void) 0)
  98. #endif // GGML_VULKAN_DEBUG
  99. struct ggml_backend_vk_context;
  100. #define MAX_PARAMETER_COUNT 12
  101. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  102. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  103. struct vk_pipeline_struct {
  104. std::string name;
  105. vk::ShaderModule shader_module;
  106. vk::PipelineLayout layout;
  107. vk::Pipeline pipeline;
  108. uint32_t push_constant_size;
  109. uint32_t parameter_count;
  110. std::array<uint32_t, 3> wg_denoms;
  111. uint32_t align;
  112. // true if fields have been set by ggml_vk_create_pipeline
  113. bool initialized {};
  114. // set to true to request the pipeline is compiled
  115. std::atomic<bool> needed {};
  116. // set to true when the shader has been compiled
  117. std::atomic<bool> compiled {};
  118. // number of registers used, extracted from pipeline executable properties
  119. uint32_t register_count {};
  120. };
  121. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  122. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  123. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  124. struct vk_matmul_pipeline_struct {
  125. vk_pipeline l, m, s;
  126. vk_pipeline a_l, a_m, a_s;
  127. // Returns true when all unaligned pipelines are null.
  128. // We only check for unaligned variants since one of the unaligned pipelines must exist
  129. // while aligned pipelines are optional
  130. bool is_empty() const {
  131. return l == nullptr && m == nullptr && s == nullptr;
  132. }
  133. };
  134. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  135. struct vk_matmul_pipeline2 {
  136. vk_matmul_pipeline2() {
  137. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  139. }
  140. vk_matmul_pipeline f32acc;
  141. vk_matmul_pipeline f16acc;
  142. };
  143. struct vk_device_struct;
  144. typedef std::shared_ptr<vk_device_struct> vk_device;
  145. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  146. struct vk_buffer_struct;
  147. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  148. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  149. struct ggml_backend_vk_buffer_type_context {
  150. std::string name;
  151. vk_device device;
  152. };
  153. struct vk_queue;
  154. // Stores command pool/buffers. There's an instance of this
  155. // for each (context,queue) pair and for each (device,queue) pair.
  156. struct vk_command_pool {
  157. void init(vk_device& device, vk_queue *q_);
  158. void destroy(vk::Device& device);
  159. vk::CommandPool pool;
  160. uint32_t cmd_buffer_idx;
  161. std::vector<vk::CommandBuffer> cmd_buffers;
  162. vk_queue *q;
  163. };
  164. // Prevent simultaneous submissions to the same queue.
  165. // This could be per vk_queue if we stopped having two vk_queue structures
  166. // sharing the same vk::Queue.
  167. static std::mutex queue_mutex;
  168. struct vk_queue {
  169. uint32_t queue_family_index;
  170. vk::Queue queue;
  171. vk_command_pool cmd_pool;
  172. vk::PipelineStageFlags stage_flags;
  173. bool transfer_only;
  174. // copy everything except the cmd_pool
  175. void copyFrom(vk_queue &other) {
  176. queue_family_index = other.queue_family_index;
  177. queue = other.queue;
  178. stage_flags = other.stage_flags;
  179. transfer_only = other.transfer_only;
  180. }
  181. };
  182. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  183. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  184. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  186. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  187. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  188. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  189. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  190. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  191. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  192. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  193. /* .is_host = */ NULL,
  194. };
  195. #ifdef GGML_VULKAN_MEMORY_DEBUG
  196. class vk_memory_logger;
  197. #endif
  198. class vk_perf_logger;
  199. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  200. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx);
  201. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  202. static constexpr uint32_t p021_max_gqa_ratio = 8;
  203. enum vk_device_architecture {
  204. OTHER,
  205. AMD_GCN,
  206. AMD_RDNA1,
  207. AMD_RDNA2,
  208. AMD_RDNA3,
  209. INTEL_XE2,
  210. NVIDIA_PRE_TURING,
  211. };
  212. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  213. vk::PhysicalDeviceProperties props = device.getProperties();
  214. if (props.vendorID == VK_VENDOR_ID_AMD) {
  215. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  216. bool amd_shader_core_properties = false;
  217. bool integer_dot_product = false;
  218. bool subgroup_size_control = false;
  219. for (const auto& properties : ext_props) {
  220. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  221. amd_shader_core_properties = true;
  222. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  223. integer_dot_product = true;
  224. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  225. subgroup_size_control = true;
  226. }
  227. }
  228. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  229. return vk_device_architecture::OTHER;
  230. }
  231. vk::PhysicalDeviceProperties2 props2;
  232. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  233. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  234. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  235. props2.pNext = &shader_core_props_amd;
  236. shader_core_props_amd.pNext = &integer_dot_props;
  237. integer_dot_props.pNext = &subgroup_size_control_props;
  238. device.getProperties2(&props2);
  239. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  240. return vk_device_architecture::AMD_GCN;
  241. }
  242. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  243. // RDNA
  244. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  245. return vk_device_architecture::AMD_RDNA1;
  246. }
  247. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  248. return vk_device_architecture::AMD_RDNA3;
  249. }
  250. return vk_device_architecture::AMD_RDNA2;
  251. }
  252. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  253. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  254. bool subgroup_size_control = false;
  255. for (const auto& properties : ext_props) {
  256. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  257. subgroup_size_control = true;
  258. }
  259. }
  260. if (!subgroup_size_control) {
  261. return vk_device_architecture::OTHER;
  262. }
  263. vk::PhysicalDeviceProperties2 props2;
  264. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  265. props2.pNext = &subgroup_size_control_props;
  266. device.getProperties2(&props2);
  267. if (subgroup_size_control_props.minSubgroupSize == 16) {
  268. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  269. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  270. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  271. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  272. return vk_device_architecture::INTEL_XE2;
  273. }
  274. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  275. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  276. bool cooperative_matrix = false;
  277. // Detect "pre-turing" based on lack of coopmat support.
  278. for (const auto& properties : ext_props) {
  279. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  280. cooperative_matrix = true;
  281. break;
  282. }
  283. }
  284. if (!cooperative_matrix) {
  285. return vk_device_architecture::NVIDIA_PRE_TURING;
  286. }
  287. }
  288. return vk_device_architecture::OTHER;
  289. }
  290. enum vk_conv_shapes {
  291. CONV_SHAPE_128x128,
  292. CONV_SHAPE_64x32,
  293. CONV_SHAPE_32x256,
  294. CONV_SHAPE_COUNT,
  295. };
  296. struct vk_conv_block_size {
  297. uint32_t K;
  298. uint32_t NPQ;
  299. uint32_t CRS;
  300. };
  301. vk_conv_block_size vk_conv_block_sizes[CONV_SHAPE_COUNT] = {
  302. // K NPQ CRS
  303. { 128, 128, 16 }, // CONV_SHAPE_128x128
  304. { 64, 32, 32 }, // CONV_SHAPE_64x32
  305. { 32, 256, 16 }, // CONV_SHAPE_32x256
  306. };
  307. enum dmmv_wg_sizes {
  308. DMMV_WG_SIZE_SUBGROUP,
  309. DMMV_WG_SIZE_LARGE,
  310. DMMV_WG_SIZE_COUNT,
  311. };
  312. enum FaCodePath {
  313. FA_SCALAR,
  314. FA_COOPMAT1,
  315. FA_COOPMAT2,
  316. };
  317. struct vk_fa_pipeline_state {
  318. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  319. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  320. uint32_t HSK, HSV;
  321. bool small_rows;
  322. FaCodePath path;
  323. bool aligned;
  324. bool f32acc;
  325. bool operator<(const vk_fa_pipeline_state &b) const {
  326. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  327. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  328. }
  329. };
  330. struct vk_conv2d_pipeline_state {
  331. vk_conv2d_pipeline_state(uint32_t s0, uint32_t s1, uint32_t p0, uint32_t p1, uint32_t d0, uint32_t d1, uint32_t KW, uint32_t KH)
  332. : s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), KW(KW), KH(KH) {}
  333. uint32_t s0, s1, p0, p1, d0, d1, KW, KH;
  334. bool operator<(const vk_conv2d_pipeline_state &b) const {
  335. return std::tie(s0, s1, p0, p1, d0, d1, KW, KH) <
  336. std::tie(b.s0, b.s1, b.p0, b.p1, b.d0, b.d1, b.KW, b.KH);
  337. }
  338. };
  339. struct vk_solve_tri_pipeline_state {
  340. vk_solve_tri_pipeline_state(uint32_t N, uint32_t K)
  341. : N(N), K(K) {}
  342. uint32_t N, K;
  343. bool operator<(const vk_solve_tri_pipeline_state &b) const {
  344. return std::tie(N, K) <
  345. std::tie(b.N, b.K);
  346. }
  347. };
  348. enum shader_reduction_mode {
  349. SHADER_REDUCTION_MODE_SHMEM,
  350. SHADER_REDUCTION_MODE_HYBRID,
  351. SHADER_REDUCTION_MODE_SUBGROUP,
  352. SHADER_REDUCTION_MODE_COUNT,
  353. };
  354. // argsort pipelines for up to 1<<10 invocations per workgroup
  355. static constexpr uint32_t num_argsort_pipelines = 11;
  356. static constexpr uint32_t num_topk_moe_pipelines = 10;
  357. static constexpr uint32_t num_topk_pipelines = 11;
  358. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  359. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  360. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  361. GGML_OP_RESHAPE };
  362. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  363. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  364. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  365. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  366. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  367. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  368. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  369. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  370. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  371. //node #982 ( GET_ROWS): ffn_moe_weights-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 (re ( 0K) [Vulka ] ffn_moe_topk-15 ( 0K) [Vulka ]
  372. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  373. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  374. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  375. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  376. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  377. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  378. { 1, 0, 0 }, // reshape->src[0] == softmax
  379. { 2, 0, 0 }, // argsort->src[0] == softmax
  380. { 3, 0, 2 }, // view->src[0] == argsort
  381. { 4, 0, 1 }, // get_rows->src[0] == reshape
  382. { 4, 1, 3 }, // get_rows->src[1] == view
  383. { 5, 0, 4 }, // reshape->src[0] == get_rows
  384. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  385. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  386. { 8, 0, 5 }, // div->src[0] == reshape
  387. { 8, 1, 7 }, // div->src[1] == clamp
  388. { 9, 0, 8 }, // reshape->src[0] == div
  389. };
  390. // same as early_softmax_norm but ending after the get_rows
  391. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  392. { 1, 0, 0 }, // reshape->src[0] == softmax
  393. { 2, 0, 0 }, // argsort->src[0] == softmax
  394. { 3, 0, 2 }, // view->src[0] == argsort
  395. { 4, 0, 1 }, // get_rows->src[0] == reshape
  396. { 4, 1, 3 }, // get_rows->src[1] == view
  397. };
  398. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  399. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  400. //node #654 ( GET_ROWS): ffn_moe_weights-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 (re ( 0K) [Vulka ] ffn_moe_topk-11 ( 0K) [Vulka ]
  401. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  402. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  403. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  404. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  405. { 1, 0, 0 }, // view->src[0] == argsort
  406. { 2, 1, 1 }, // get_rows->src[1] == view
  407. { 3, 0, 2 }, // reshape->src[0] == get_rows
  408. { 4, 0, 3 }, // soft_max->src[0] == reshape
  409. { 5, 0, 4 }, // reshape->src[0] == soft_max
  410. };
  411. enum topk_moe_mode {
  412. TOPK_MOE_EARLY_SOFTMAX,
  413. TOPK_MOE_EARLY_SOFTMAX_NORM,
  414. TOPK_MOE_LATE_SOFTMAX,
  415. TOPK_MOE_COUNT,
  416. };
  417. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  418. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  419. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  420. TOPK_MOE_LATE_SOFTMAX;
  421. return mode;
  422. }
  423. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  424. { 1, 0, 0 }, // view->src[0] == rope
  425. { 2, 0, 1 }, // set_rows->src[0] == view
  426. };
  427. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  428. { 1, 0, 0 }, // mul->src[0] == rms
  429. { 2, 0, 1 }, // rope->src[0] == mul
  430. { 3, 0, 2 }, // view->src[0] == rope
  431. { 4, 0, 3 }, // set_rows->src[0] == view
  432. };
  433. struct vk_device_struct {
  434. std::recursive_mutex mutex;
  435. vk::PhysicalDevice physical_device;
  436. vk::PhysicalDeviceProperties properties;
  437. std::string name;
  438. uint64_t max_memory_allocation_size;
  439. uint64_t max_buffer_size;
  440. uint64_t suballocation_block_size;
  441. bool fp16;
  442. bool bf16;
  443. bool pipeline_robustness;
  444. bool memory_priority;
  445. vk::Device device;
  446. uint32_t vendor_id;
  447. vk::DriverId driver_id;
  448. vk_device_architecture architecture;
  449. vk_queue compute_queue;
  450. vk_queue transfer_queue;
  451. bool single_queue;
  452. bool support_async;
  453. uint32_t subgroup_size;
  454. uint32_t subgroup_size_log2;
  455. uint32_t shader_core_count;
  456. bool uma;
  457. bool prefer_host_memory;
  458. bool float_controls_rte_fp16;
  459. bool subgroup_arithmetic;
  460. bool subgroup_shuffle;
  461. bool subgroup_ballot;
  462. bool subgroup_clustered;
  463. bool subgroup_vote;
  464. bool multi_add;
  465. bool shader_int64;
  466. bool buffer_device_address;
  467. bool vulkan_memory_model;
  468. bool add_rms_fusion;
  469. uint32_t partials_binding_alignment;
  470. bool integer_dot_product;
  471. // 0: default, 1: force mmvq, -1: disable mmvq
  472. int32_t mmvq_mode;
  473. bool subgroup_size_control;
  474. uint32_t subgroup_min_size;
  475. uint32_t subgroup_max_size;
  476. bool subgroup_require_full_support;
  477. // floor(log2(maxComputeWorkGroupInvocations))
  478. uint32_t max_workgroup_size_log2 {};
  479. bool coopmat_support;
  480. bool coopmat_acc_f32_support {};
  481. bool coopmat_acc_f16_support {};
  482. bool coopmat_bf16_support {};
  483. bool coopmat_support_16x16x16_f16acc {};
  484. bool coopmat_support_16x16x16_f32acc {};
  485. bool coopmat1_fa_support {};
  486. uint32_t coopmat_m;
  487. uint32_t coopmat_n;
  488. uint32_t coopmat_k;
  489. bool coopmat_int_support;
  490. uint32_t coopmat_int_m;
  491. uint32_t coopmat_int_n;
  492. uint32_t coopmat_int_k;
  493. bool coopmat2;
  494. bool pipeline_executable_properties_support {};
  495. size_t idx;
  496. bool mul_mat_l[GGML_TYPE_COUNT];
  497. bool mul_mat_m[GGML_TYPE_COUNT];
  498. bool mul_mat_s[GGML_TYPE_COUNT];
  499. bool mul_mat_id_l[GGML_TYPE_COUNT];
  500. bool mul_mat_id_m[GGML_TYPE_COUNT];
  501. bool mul_mat_id_s[GGML_TYPE_COUNT];
  502. vk::DescriptorSetLayout dsl;
  503. vk_matmul_pipeline pipeline_matmul_f32 {};
  504. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  505. vk_matmul_pipeline pipeline_matmul_bf16 {};
  506. vk_matmul_pipeline2 pipeline_matmul_f16;
  507. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  508. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  509. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  510. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  511. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  512. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  513. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  514. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  515. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  516. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  517. vk_pipeline pipeline_matmul_split_k_reduce;
  518. vk_pipeline pipeline_quantize_q8_1_x4;
  519. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  520. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  521. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  522. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  523. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  524. vk_pipeline pipeline_dequant_mul_mat_vec_id_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  525. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  526. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  527. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  528. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  529. vk_pipeline pipeline_acc_f32;
  530. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  531. vk_pipeline pipeline_add[2][2][2];
  532. vk_pipeline pipeline_add_norepeat[2][2][2];
  533. vk_pipeline pipeline_sub[2][2][2];
  534. vk_pipeline pipeline_sub_norepeat[2][2][2];
  535. vk_pipeline pipeline_mul[2][2][2];
  536. vk_pipeline pipeline_mul_norepeat[2][2][2];
  537. vk_pipeline pipeline_div[2][2][2];
  538. vk_pipeline pipeline_div_norepeat[2][2][2];
  539. vk_pipeline pipeline_add_rms[2][2][2];
  540. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  541. // indexed by num_additional_fused_ops == num_adds - 1
  542. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  543. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  544. vk_pipeline pipeline_add_id_f32;
  545. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  546. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32;
  547. vk_pipeline pipeline_scale_f32;
  548. vk_pipeline pipeline_sqr_f32;
  549. vk_pipeline pipeline_sqrt_f32;
  550. vk_pipeline pipeline_sin_f32;
  551. vk_pipeline pipeline_cos_f32;
  552. vk_pipeline pipeline_log[2];
  553. vk_pipeline pipeline_tri[2];
  554. vk_pipeline pipeline_diag[2];
  555. vk_pipeline pipeline_clamp_f32;
  556. vk_pipeline pipeline_pad_f32;
  557. vk_pipeline pipeline_roll_f32;
  558. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  559. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
  560. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
  561. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  562. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  563. vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
  564. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  565. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  566. vk_pipeline pipeline_norm_f32;
  567. vk_pipeline pipeline_group_norm_f32;
  568. vk_pipeline pipeline_rms_norm_f32;
  569. vk_pipeline pipeline_rms_norm_mul_f32;
  570. vk_pipeline pipeline_rms_norm_partials_f32;
  571. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  572. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  573. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  574. vk_pipeline pipeline_rms_norm_back_f32;
  575. vk_pipeline pipeline_l2_norm_f32;
  576. // [src/dst 0=fp32,1=fp16]
  577. vk_pipeline pipeline_exp[2];
  578. vk_pipeline pipeline_gelu[2];
  579. vk_pipeline pipeline_gelu_erf[2];
  580. vk_pipeline pipeline_gelu_quick[2];
  581. vk_pipeline pipeline_silu[2];
  582. vk_pipeline pipeline_relu[2];
  583. vk_pipeline pipeline_neg[2];
  584. vk_pipeline pipeline_tanh[2];
  585. vk_pipeline pipeline_sigmoid[2];
  586. vk_pipeline pipeline_hardsigmoid[2];
  587. vk_pipeline pipeline_hardswish[2];
  588. vk_pipeline pipeline_abs[2];
  589. vk_pipeline pipeline_softplus[2];
  590. vk_pipeline pipeline_step[2];
  591. vk_pipeline pipeline_round[2];
  592. vk_pipeline pipeline_ceil[2];
  593. vk_pipeline pipeline_floor[2];
  594. vk_pipeline pipeline_trunc[2];
  595. vk_pipeline pipeline_add1_f16_f16;
  596. vk_pipeline pipeline_add1_f16_f32;
  597. vk_pipeline pipeline_add1_f32_f32;
  598. vk_pipeline pipeline_arange_f32;
  599. vk_pipeline pipeline_fill_f32;
  600. vk_pipeline pipeline_geglu[2];
  601. vk_pipeline pipeline_reglu[2];
  602. vk_pipeline pipeline_swiglu[2];
  603. vk_pipeline pipeline_swiglu_oai[2];
  604. vk_pipeline pipeline_geglu_erf[2];
  605. vk_pipeline pipeline_geglu_quick[2];
  606. vk_pipeline pipeline_leaky_relu_f32;
  607. vk_pipeline pipeline_silu_back_f32;
  608. vk_pipeline pipeline_diag_mask_inf_f32;
  609. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  610. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  611. vk_pipeline pipeline_soft_max_back_f32;
  612. vk_pipeline pipeline_soft_max_large1_f32, pipeline_soft_max_large1_f32_f16;
  613. vk_pipeline pipeline_soft_max_large2_f32, pipeline_soft_max_large2_f32_f16;
  614. vk_pipeline pipeline_soft_max_large3_f32, pipeline_soft_max_large3_f32_f16;
  615. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  616. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  617. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  618. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  619. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  620. vk_pipeline pipeline_argsort_large_f32[num_argsort_pipelines];
  621. vk_pipeline pipeline_topk_f32[num_topk_pipelines];
  622. vk_pipeline pipeline_sum_rows_f32;
  623. vk_pipeline pipeline_cumsum_f32;
  624. vk_pipeline pipeline_argmax_f32;
  625. vk_pipeline pipeline_count_equal_i32;
  626. std::map<vk_solve_tri_pipeline_state, vk_pipeline> pipeline_solve_tri_f32;
  627. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  628. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  629. vk_pipeline pipeline_timestep_embedding_f32;
  630. vk_pipeline pipeline_conv_transpose_1d_f32;
  631. vk_pipeline pipeline_pool2d_f32;
  632. vk_pipeline pipeline_rwkv_wkv6_f32;
  633. vk_pipeline pipeline_rwkv_wkv7_f32;
  634. vk_pipeline pipeline_ssm_scan_f32_d128;
  635. vk_pipeline pipeline_ssm_scan_f32_d256;
  636. vk_pipeline pipeline_ssm_conv_f32;
  637. vk_pipeline pipeline_opt_step_adamw_f32;
  638. vk_pipeline pipeline_opt_step_sgd_f32;
  639. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  640. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  641. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  642. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  643. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  644. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  645. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  646. vk_pipeline pipeline_flash_attn_split_k_reduce;
  647. // [2] is for whether to take n_experts from spec constant (0) or push constant (1)
  648. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT][2];
  649. std::vector<vk_pipeline_ref> all_pipelines;
  650. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  651. vk::Fence fence;
  652. vk_buffer sync_staging;
  653. ggml_backend_buffer_type buffer_type;
  654. bool disable_fusion;
  655. bool disable_host_visible_vidmem;
  656. bool allow_sysmem_fallback;
  657. bool disable_graph_optimize;
  658. #ifdef GGML_VULKAN_MEMORY_DEBUG
  659. std::unique_ptr<vk_memory_logger> memory_logger;
  660. #endif
  661. ~vk_device_struct() {
  662. VK_LOG_DEBUG("destroy device " << name);
  663. device.destroyFence(fence);
  664. ggml_vk_destroy_buffer(sync_staging);
  665. compute_queue.cmd_pool.destroy(device);
  666. transfer_queue.cmd_pool.destroy(device);
  667. for (auto& pipeline : all_pipelines) {
  668. if (pipeline.expired()) {
  669. continue;
  670. }
  671. vk_pipeline pl = pipeline.lock();
  672. ggml_vk_destroy_pipeline(device, pl);
  673. }
  674. all_pipelines.clear();
  675. device.destroyDescriptorSetLayout(dsl);
  676. device.destroy();
  677. }
  678. };
  679. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  680. cmd_buffer_idx = 0;
  681. q = q_;
  682. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  683. pool = device->device.createCommandPool(command_pool_create_info);
  684. }
  685. void vk_command_pool::destroy(vk::Device& device) {
  686. device.destroyCommandPool(pool);
  687. pool = nullptr;
  688. cmd_buffers.clear();
  689. }
  690. struct vk_buffer_struct {
  691. vk::Buffer buffer = VK_NULL_HANDLE;
  692. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  693. vk::MemoryPropertyFlags memory_property_flags;
  694. void * ptr;
  695. size_t size = 0;
  696. vk::DeviceAddress bda_addr {};
  697. vk_device device;
  698. ~vk_buffer_struct() {
  699. if (size == 0) {
  700. return;
  701. }
  702. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  703. device->device.freeMemory(device_memory);
  704. device->device.destroyBuffer(buffer);
  705. }
  706. };
  707. struct vk_subbuffer {
  708. vk_buffer buffer;
  709. uint64_t offset;
  710. uint64_t size;
  711. operator vk::DescriptorBufferInfo() const {
  712. return { buffer->buffer, offset, size };
  713. }
  714. };
  715. struct vk_semaphore {
  716. vk::Semaphore s;
  717. uint64_t value;
  718. };
  719. struct vk_submission {
  720. vk::CommandBuffer buffer;
  721. std::vector<vk_semaphore> wait_semaphores;
  722. std::vector<vk_semaphore> signal_semaphores;
  723. };
  724. typedef std::vector<vk_submission> vk_sequence;
  725. struct vk_mat_mat_push_constants {
  726. uint32_t M; uint32_t N; uint32_t K;
  727. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  728. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  729. uint32_t k_split;
  730. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  731. uint32_t padded_N;
  732. };
  733. #define MAT_VEC_FUSION_FLAGS_BIAS0 0x1
  734. #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
  735. #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
  736. #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
  737. struct vk_mat_vec_push_constants {
  738. uint32_t ncols;
  739. uint32_t stride_a;
  740. uint32_t stride_b;
  741. uint32_t stride_d;
  742. uint32_t batch_stride_a;
  743. uint32_t batch_stride_b;
  744. uint32_t batch_stride_d;
  745. uint32_t fusion_flags;
  746. uint32_t ne02;
  747. uint32_t ne12;
  748. uint32_t broadcast2;
  749. uint32_t broadcast3;
  750. };
  751. struct vk_mat_vec_p021_push_constants {
  752. uint32_t ncols_x;
  753. uint32_t nrows_x;
  754. uint32_t nchannels_x;
  755. uint32_t nchannels_y;
  756. uint32_t b_offset;
  757. uint32_t d_offset;
  758. uint32_t fusion_flags;
  759. };
  760. struct vk_mat_vec_nc_push_constants {
  761. uint32_t ncols_x;
  762. uint32_t nrows_x;
  763. uint32_t row_stride_x;
  764. uint32_t channel_stride_x;
  765. uint32_t channel_stride_y;
  766. uint32_t channel_x_divisor;
  767. uint32_t ne12;
  768. uint32_t b_offset;
  769. uint32_t d_offset;
  770. uint32_t nb03;
  771. uint32_t nb13;
  772. uint32_t nb23;
  773. uint32_t fusion_flags;
  774. };
  775. struct vk_mat_mat_id_push_constants {
  776. uint32_t M; uint32_t N; uint32_t K;
  777. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  778. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  779. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  780. uint32_t padded_N;
  781. };
  782. struct vk_mat_vec_id_push_constants {
  783. uint32_t ncols;
  784. uint32_t stride_a;
  785. uint32_t stride_b;
  786. uint32_t stride_d;
  787. uint32_t batch_stride_a;
  788. uint32_t batch_stride_b;
  789. uint32_t batch_stride_d;
  790. uint32_t fusion_flags;
  791. uint32_t nei0;
  792. uint32_t ne11;
  793. };
  794. struct vk_flash_attn_push_constants {
  795. uint32_t N;
  796. uint32_t KV;
  797. uint32_t ne1;
  798. uint32_t ne2;
  799. uint32_t ne3;
  800. uint32_t neq2;
  801. uint32_t neq3;
  802. uint32_t nek2;
  803. uint32_t nek3;
  804. uint32_t nev2;
  805. uint32_t nev3;
  806. uint32_t nem1;
  807. uint32_t nem2;
  808. uint32_t nem3;
  809. uint32_t nb01;
  810. uint32_t nb02;
  811. uint32_t nb03;
  812. uint32_t nb11;
  813. uint32_t nb12;
  814. uint32_t nb13;
  815. uint32_t nb21;
  816. uint32_t nb22;
  817. uint32_t nb23;
  818. float scale;
  819. float max_bias;
  820. float logit_softcap;
  821. uint32_t mask_n_head_log2;
  822. float m0;
  823. float m1;
  824. uint32_t gqa_ratio;
  825. uint32_t split_kv;
  826. uint32_t k_num;
  827. };
  828. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  829. struct vk_op_push_constants {
  830. uint32_t KX;
  831. uint32_t KY;
  832. float param1;
  833. float param2;
  834. };
  835. struct vk_op_glu_push_constants {
  836. uint32_t N;
  837. uint32_t ne00;
  838. uint32_t ne20;
  839. uint32_t mode; // 0: default, 1: swapped, 2: split
  840. float alpha; // for swiglu_oai
  841. float limit;
  842. };
  843. struct vk_op_unary_push_constants {
  844. uint32_t ne;
  845. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  846. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  847. uint32_t misalign_offsets;
  848. float param1; float param2;
  849. uint32_t ne0_012mp; uint32_t ne0_012L;
  850. uint32_t ne0_01mp; uint32_t ne0_01L;
  851. uint32_t ne0_0mp; uint32_t ne0_0L;
  852. uint32_t ne1_012mp; uint32_t ne1_012L;
  853. uint32_t ne1_01mp; uint32_t ne1_01L;
  854. uint32_t ne1_0mp; uint32_t ne1_0L;
  855. };
  856. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  857. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  858. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  859. ne = ne != 0 ? ne : ggml_nelements(dst);
  860. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  861. vk_op_unary_push_constants p{};
  862. p.ne = (uint32_t)ne;
  863. size_t src0_tsize = ggml_type_size(src0->type);
  864. p.ne00 = (uint32_t)src0->ne[0];
  865. p.ne01 = (uint32_t)src0->ne[1];
  866. p.ne02 = (uint32_t)src0->ne[2];
  867. p.ne03 = (uint32_t)src0->ne[3];
  868. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  869. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  870. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  871. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  872. size_t dst_tsize = ggml_type_size(dst->type);
  873. p.ne10 = (uint32_t)dst->ne[0];
  874. p.ne11 = (uint32_t)dst->ne[1];
  875. p.ne12 = (uint32_t)dst->ne[2];
  876. p.ne13 = (uint32_t)dst->ne[3];
  877. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  878. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  879. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  880. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  881. return p; // offsets are initialized later in ggml_vk_op
  882. }
  883. struct vk_op_pad_push_constants {
  884. uint32_t ne;
  885. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  886. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  887. uint32_t misalign_offsets;
  888. uint32_t circular;
  889. uint32_t lp0; uint32_t rp0;
  890. uint32_t lp1; uint32_t rp1;
  891. uint32_t lp2; uint32_t rp2;
  892. uint32_t lp3; uint32_t rp3;
  893. };
  894. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  895. int64_t ne = ggml_nelements(dst);
  896. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  897. vk_op_pad_push_constants p{};
  898. p.ne = (uint32_t)ne;
  899. size_t src0_tsize = ggml_type_size(src0->type);
  900. p.ne00 = (uint32_t)src0->ne[0];
  901. p.ne01 = (uint32_t)src0->ne[1];
  902. p.ne02 = (uint32_t)src0->ne[2];
  903. p.ne03 = (uint32_t)src0->ne[3];
  904. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  905. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  906. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  907. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  908. size_t dst_tsize = ggml_type_size(dst->type);
  909. p.ne10 = (uint32_t)dst->ne[0];
  910. p.ne11 = (uint32_t)dst->ne[1];
  911. p.ne12 = (uint32_t)dst->ne[2];
  912. p.ne13 = (uint32_t)dst->ne[3];
  913. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  914. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  915. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  916. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  917. p.lp0 = dst->op_params[0];
  918. p.rp0 = dst->op_params[1];
  919. p.lp1 = dst->op_params[2];
  920. p.rp1 = dst->op_params[3];
  921. p.lp2 = dst->op_params[4];
  922. p.rp2 = dst->op_params[5];
  923. p.lp3 = dst->op_params[6];
  924. p.rp3 = dst->op_params[7];
  925. p.circular = dst->op_params[8];
  926. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  927. }
  928. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  929. // Precompute mp (m' in the paper) and L such that division
  930. // can be computed using a multiply (high 32b of 64b result)
  931. // and a shift:
  932. //
  933. // n/d = (mulhi(n, mp) + n) >> L;
  934. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  935. {
  936. // compute L = ceil(log2(d));
  937. L = 0;
  938. while (L < 32 && (uint32_t{1} << L) < d) {
  939. L++;
  940. }
  941. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  942. }
  943. template <typename T> void init_pushconst_fastdiv(T &p) {
  944. GGML_UNUSED(p);
  945. static_assert(!std::is_const<T>::value, "unexpected type");
  946. }
  947. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  948. // Compute magic values to divide by these six numbers.
  949. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  950. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  951. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  952. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  953. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  954. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  955. }
  956. struct vk_op_binary_push_constants {
  957. uint32_t ne;
  958. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  959. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  960. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  961. uint32_t misalign_offsets;
  962. float param1; float param2; int32_t param3;
  963. };
  964. struct vk_op_multi_add_push_constants {
  965. // shape for dst
  966. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  967. // strides for srcs+dst
  968. uint32_t nb[MAX_PARAMETER_COUNT][4];
  969. uint32_t rms_partials;
  970. };
  971. // update multi_add.comp if this changes
  972. static_assert(MAX_PARAMETER_COUNT == 12);
  973. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  974. struct vk_op_topk_moe_push_constants {
  975. uint32_t n_rows;
  976. uint32_t n_experts_push;
  977. uint32_t n_expert_used;
  978. float clamp_min;
  979. float clamp_max;
  980. };
  981. struct vk_op_add_id_push_constants {
  982. uint32_t ne0;
  983. uint32_t ne1;
  984. uint32_t s01;
  985. uint32_t s02;
  986. uint32_t s11;
  987. uint32_t s21;
  988. };
  989. struct vk_op_diag_mask_push_constants {
  990. uint32_t ncols;
  991. uint32_t rows_per_channel;
  992. int32_t n_past;
  993. };
  994. struct vk_op_rope_push_constants {
  995. uint32_t rope_mode;
  996. uint32_t ncols;
  997. uint32_t n_dims;
  998. float freq_scale;
  999. uint32_t p_delta_rows;
  1000. float freq_base;
  1001. float ext_factor;
  1002. float attn_factor;
  1003. float corr_dims[2];
  1004. float theta_scale;
  1005. uint32_t has_ff;
  1006. uint32_t ne02;
  1007. uint32_t s1;
  1008. uint32_t s2;
  1009. int32_t sections[4];
  1010. uint32_t is_imrope;
  1011. uint32_t is_back;
  1012. uint32_t set_rows_stride;
  1013. };
  1014. // For fused rms_norm+mul+rope(+view+set_rows)
  1015. struct vk_op_rms_norm_mul_rope_push_constants {
  1016. vk_op_binary_push_constants bin;
  1017. vk_op_rope_push_constants rope;
  1018. };
  1019. struct vk_op_soft_max_push_constants {
  1020. uint32_t KX;
  1021. uint32_t KY;
  1022. uint32_t ne00;
  1023. uint32_t ne01;
  1024. uint32_t ne02;
  1025. uint32_t ne12;
  1026. uint32_t ne13;
  1027. uint32_t nb11;
  1028. uint32_t nb12;
  1029. uint32_t nb13;
  1030. float scale;
  1031. float max_bias;
  1032. float m0;
  1033. float m1;
  1034. uint32_t n_head_log2;
  1035. uint32_t nrows_x;
  1036. uint32_t has_sinks;
  1037. };
  1038. struct vk_op_argsort_push_constants {
  1039. uint32_t ncols;
  1040. uint32_t ncols_padded;
  1041. uint32_t ncols_padded_log2;
  1042. uint32_t nrows;
  1043. uint32_t order;
  1044. uint32_t outer_start;
  1045. uint32_t outer_end;
  1046. uint32_t inner_start;
  1047. uint32_t inner_end;
  1048. };
  1049. struct vk_op_topk_push_constants {
  1050. uint32_t orig_ncols;
  1051. uint32_t ncols_input;
  1052. uint32_t ncols_output;
  1053. uint32_t k;
  1054. uint32_t nrows;
  1055. uint32_t first_pass;
  1056. uint32_t last_pass;
  1057. };
  1058. struct vk_op_im2col_push_constants {
  1059. uint64_t dst_addr;
  1060. uint32_t batch_offset; uint32_t offset_delta;
  1061. uint32_t IC;
  1062. uint32_t IW; uint32_t IH;
  1063. uint32_t OW; uint32_t OH;
  1064. uint32_t KW; uint32_t KH;
  1065. uint32_t pelements;
  1066. uint32_t CHW;
  1067. int32_t s0; int32_t s1;
  1068. int32_t p0; int32_t p1;
  1069. int32_t d0; int32_t d1;
  1070. };
  1071. struct vk_op_im2col_3d_push_constants {
  1072. uint64_t dst_addr;
  1073. uint32_t nb10;
  1074. uint32_t nb11;
  1075. uint32_t nb12;
  1076. uint32_t nb13;
  1077. uint32_t s0;
  1078. uint32_t s1;
  1079. uint32_t s2;
  1080. uint32_t p0;
  1081. uint32_t p1;
  1082. uint32_t p2;
  1083. uint32_t d0;
  1084. uint32_t d1;
  1085. uint32_t d2;
  1086. uint32_t IW;
  1087. uint32_t IH;
  1088. uint32_t ID;
  1089. uint32_t IC;
  1090. uint32_t KW;
  1091. uint32_t OH;
  1092. uint32_t KD_KH_KW;
  1093. uint32_t KH_KW;
  1094. uint32_t IC_KD_KH_KW;
  1095. uint32_t N_OD_OH;
  1096. uint32_t OD_OH;
  1097. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1098. uint32_t OH_OW_IC_KD_KH_KW;
  1099. uint32_t OW_IC_KD_KH_KW;
  1100. uint32_t misalign_offsets;
  1101. };
  1102. struct vk_op_timestep_embedding_push_constants {
  1103. uint32_t nb1;
  1104. uint32_t dim;
  1105. uint32_t max_period;
  1106. };
  1107. struct vk_op_conv_transpose_1d_push_constants {
  1108. uint32_t Cout;
  1109. uint32_t Cin;
  1110. uint32_t K;
  1111. uint32_t L;
  1112. uint32_t KL;
  1113. uint32_t nb01;
  1114. uint32_t nb02;
  1115. uint32_t nb11;
  1116. uint32_t nb1;
  1117. int32_t s0;
  1118. };
  1119. struct vk_op_pool2d_push_constants {
  1120. uint32_t IW; uint32_t IH;
  1121. uint32_t OW; uint32_t OH;
  1122. uint32_t OC;
  1123. uint32_t pelements;
  1124. uint32_t op;
  1125. int32_t k0; int32_t k1;
  1126. int32_t s0; int32_t s1;
  1127. int32_t p0; int32_t p1;
  1128. };
  1129. struct vk_op_rwkv_wkv6_push_constants {
  1130. uint32_t B;
  1131. uint32_t T;
  1132. uint32_t C;
  1133. uint32_t H;
  1134. };
  1135. struct vk_op_rwkv_wkv7_push_constants {
  1136. uint32_t B;
  1137. uint32_t T;
  1138. uint32_t C;
  1139. uint32_t H;
  1140. };
  1141. struct vk_op_ssm_scan_push_constants {
  1142. uint32_t nb02, nb03, nb12, nb13;
  1143. uint32_t nb21, nb22, nb31;
  1144. uint32_t nb42, nb43, nb52, nb53;
  1145. uint32_t s_off;
  1146. uint32_t n_head, d_head, n_group, n_tok;
  1147. };
  1148. struct vk_op_ssm_conv_push_constants {
  1149. uint32_t nb01, nb02;
  1150. uint32_t nb11;
  1151. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1152. uint32_t nc, ncs, nr, n_t, n_s;
  1153. };
  1154. struct vk_op_conv2d_push_constants {
  1155. uint32_t Cout;
  1156. uint32_t Cin;
  1157. uint32_t N;
  1158. uint32_t W;
  1159. uint32_t H;
  1160. uint32_t OW;
  1161. uint32_t OH;
  1162. uint32_t nb01;
  1163. uint32_t nb02;
  1164. uint32_t nb03;
  1165. uint32_t nb11;
  1166. uint32_t nb12;
  1167. uint32_t nb13;
  1168. uint32_t nb1;
  1169. uint32_t nb2;
  1170. uint32_t nb3;
  1171. // init_fastdiv_values constants for dividing by OW, OW*OH
  1172. uint32_t OWmp; uint32_t OWL;
  1173. uint32_t OWOHmp; uint32_t OWOHL;
  1174. };
  1175. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1176. // Compute magic values to divide by OW, OW*OH
  1177. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1178. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1179. }
  1180. struct vk_op_conv2d_dw_push_constants {
  1181. uint32_t ne;
  1182. uint32_t batches;
  1183. uint32_t channels;
  1184. uint32_t dst_w;
  1185. uint32_t dst_h;
  1186. uint32_t src_w;
  1187. uint32_t src_h;
  1188. uint32_t knl_w;
  1189. uint32_t knl_h;
  1190. int32_t stride_x;
  1191. int32_t stride_y;
  1192. int32_t pad_x;
  1193. int32_t pad_y;
  1194. int32_t dilation_x;
  1195. int32_t dilation_y;
  1196. };
  1197. struct vk_op_upscale_push_constants {
  1198. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1199. uint32_t ne00; uint32_t ne01;
  1200. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1201. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1202. float sf0; float sf1; float sf2; float sf3;
  1203. float pixel_offset;
  1204. };
  1205. struct vk_op_sum_rows_push_constants
  1206. {
  1207. uint32_t n_cols;
  1208. uint32_t ne01, ne02;
  1209. uint32_t nb01, nb02, nb03;
  1210. uint32_t nb11, nb12, nb13;
  1211. float weight;
  1212. uint32_t misalign_offsets;
  1213. uint32_t ne0_12mp, ne0_12L;
  1214. uint32_t ne0_1mp, ne0_1L;
  1215. };
  1216. static vk_op_sum_rows_push_constants vk_op_sum_rows_push_constants_init(const ggml_tensor * src, const ggml_tensor * dst, int64_t n_cols) {
  1217. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1218. vk_op_sum_rows_push_constants p = {};
  1219. p.n_cols = (uint32_t)n_cols;
  1220. p.ne01 = (uint32_t)src->ne[1];
  1221. p.ne02 = (uint32_t)src->ne[2];
  1222. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1223. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1224. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1225. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1226. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1227. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1228. p.weight = 1.0f;
  1229. return p;
  1230. }
  1231. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1232. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1233. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1234. }
  1235. // Allow pre-recording command buffers
  1236. struct vk_staging_memcpy {
  1237. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1238. void * dst;
  1239. const void * src;
  1240. size_t n;
  1241. };
  1242. struct vk_staging_memset {
  1243. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1244. void * dst;
  1245. uint32_t val;
  1246. size_t n;
  1247. };
  1248. struct vk_context_struct {
  1249. vk_submission * s;
  1250. std::vector<vk_sequence> seqs;
  1251. int exit_tensor_idx;
  1252. std::vector<vk_staging_memcpy> in_memcpys;
  1253. std::vector<vk_staging_memcpy> out_memcpys;
  1254. std::vector<vk_staging_memset> memsets;
  1255. vk_command_pool * p {};
  1256. };
  1257. typedef std::shared_ptr<vk_context_struct> vk_context;
  1258. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1259. struct ggml_vk_garbage_collector {
  1260. std::vector<vk_semaphore> tl_semaphores;
  1261. std::vector<vk_semaphore> semaphores;
  1262. std::vector<vk::Event> events;
  1263. std::vector<vk_context> contexts;
  1264. };
  1265. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1266. static void ggml_vk_load_shaders(vk_device& device);
  1267. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1268. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1269. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1270. static std::string format_size(size_t size) {
  1271. const size_t kib = 1024;
  1272. const size_t mib = kib * 1024;
  1273. const size_t gib = mib * 1024;
  1274. std::ostringstream oss;
  1275. oss << std::fixed << std::setprecision(2);
  1276. if (size >= gib) {
  1277. oss << static_cast<double>(size) / gib << " GiB";
  1278. } else if (size >= mib) {
  1279. oss << static_cast<double>(size) / mib << " MiB";
  1280. } else if (size >= kib) {
  1281. oss << static_cast<double>(size) / kib << " KiB";
  1282. } else {
  1283. oss << size << " B";
  1284. }
  1285. return oss.str();
  1286. }
  1287. class vk_memory_logger {
  1288. public:
  1289. vk_memory_logger(): total_device(0), total_host(0) {}
  1290. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1291. void log_deallocation(vk_buffer_ref buf_ref);
  1292. private:
  1293. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1294. size_t total_device;
  1295. size_t total_host;
  1296. };
  1297. #else
  1298. #define VK_LOG_MEMORY(msg) ((void) 0)
  1299. #endif // GGML_VULKAN_MEMORY_DEBUG
  1300. static bool vk_perf_logger_enabled = false;
  1301. // number of calls between perf logger prints
  1302. static uint32_t vk_perf_logger_frequency = 1;
  1303. class vk_perf_logger {
  1304. public:
  1305. void print_timings(bool force = false) {
  1306. if (timings.empty()) {
  1307. return;
  1308. }
  1309. print_count++;
  1310. if ((print_count % vk_perf_logger_frequency) != 0 && !force) {
  1311. return;
  1312. }
  1313. print_count = 0;
  1314. uint64_t total_all_op_times = 0;
  1315. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1316. for (const auto & t : timings) {
  1317. uint64_t total_op_times = 0;
  1318. for (const auto & time : t.second) {
  1319. total_op_times += time;
  1320. }
  1321. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1322. << " us";
  1323. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1324. auto it = flops.find(t.first);
  1325. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1326. uint64_t total_op_flops = 0;
  1327. for (const auto & elem : it->second) {
  1328. total_op_flops += elem;
  1329. }
  1330. std::cerr << " ("
  1331. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1332. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1333. << " GFLOPS/s)";
  1334. }
  1335. total_all_op_times += total_op_times;
  1336. std::cerr << std::endl;
  1337. }
  1338. if (timings.size() > 0) {
  1339. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1340. }
  1341. timings.clear();
  1342. flops.clear();
  1343. }
  1344. void log_timing(const ggml_tensor * node, const char *fusion_name, uint64_t time) {
  1345. std::string fusion_str;
  1346. if (fusion_name) {
  1347. fusion_str = fusion_name + std::string(" ");
  1348. }
  1349. if (node->op == GGML_OP_UNARY) {
  1350. timings[fusion_str + ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1351. return;
  1352. }
  1353. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1354. const uint64_t m = node->ne[0];
  1355. const uint64_t n = node->ne[1];
  1356. const uint64_t k = node->src[1]->ne[0];
  1357. const uint64_t batch = node->ne[2] * node->ne[3];
  1358. std::string name = ggml_op_name(node->op);
  1359. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1360. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1361. name += "_VEC";
  1362. }
  1363. name += " ";
  1364. name += ggml_type_name(node->src[0]->type);
  1365. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1366. if (node->op == GGML_OP_MUL_MAT_ID) {
  1367. name += " n_expert=" + std::to_string(node->src[0]->ne[2]);
  1368. }
  1369. if (batch > 1) {
  1370. name += " batch=" + std::to_string(batch);
  1371. }
  1372. name = fusion_str + name;
  1373. timings[name].push_back(time);
  1374. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1375. return;
  1376. }
  1377. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1378. std::string name = ggml_op_name(node->op);
  1379. ggml_tensor * knl = node->src[0];
  1380. uint64_t OW = node->ne[0];
  1381. uint64_t OH = node->ne[1];
  1382. uint64_t N = node->ne[3];
  1383. uint64_t Cout = node->ne[2];
  1384. uint64_t KW = knl->ne[0];
  1385. uint64_t KH = knl->ne[1];
  1386. uint64_t Cin = node->src[1]->ne[2];
  1387. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1388. uint64_t size_M = Cout;
  1389. uint64_t size_K = Cin * KW * KH;
  1390. uint64_t size_N = N * OW * OH;
  1391. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1392. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1393. ", N=N*OW*OH=" + std::to_string(size_N);
  1394. name = fusion_str + name;
  1395. flops[name].push_back(n_flops);
  1396. timings[name].push_back(time);
  1397. return;
  1398. }
  1399. if (node->op == GGML_OP_RMS_NORM) {
  1400. std::string name = ggml_op_name(node->op);
  1401. name += "(" + std::to_string(node->ne[0]) + "," + std::to_string(node->ne[1]) + "," + std::to_string(node->ne[2]) + "," + std::to_string(node->ne[3]) + ")";
  1402. name = fusion_str + name;
  1403. timings[name].push_back(time);
  1404. return;
  1405. }
  1406. if (node->op == GGML_OP_FLASH_ATTN_EXT) {
  1407. const ggml_tensor * dst = node;
  1408. const ggml_tensor * q = node->src[0];
  1409. const ggml_tensor * k = node->src[1];
  1410. const ggml_tensor * v = node->src[2];
  1411. const ggml_tensor * m = node->src[3];
  1412. std::stringstream name;
  1413. name << fusion_str;
  1414. name << ggml_op_name(node->op) <<
  1415. " dst(" << dst->ne[0] << "," << dst->ne[1] << "," << dst->ne[2] << "," << dst->ne[3] << "), " <<
  1416. " q(" << q->ne[0] << "," << q->ne[1] << "," << q->ne[2] << "," << q->ne[3] << "), " <<
  1417. " k(" << k->ne[0] << "," << k->ne[1] << "," << k->ne[2] << "," << k->ne[3] << "), " <<
  1418. " v(" << v->ne[0] << "," << v->ne[1] << "," << v->ne[2] << "," << v->ne[3] << "), " <<
  1419. " m(" << (m?m->ne[0]:0) << "," << (m?m->ne[1]:0) << "," << (m?m->ne[2]:0) << "," << (m?m->ne[3]:0) << ")";
  1420. timings[name.str()].push_back(time);
  1421. return;
  1422. }
  1423. if (node->op == GGML_OP_TOP_K) {
  1424. std::stringstream name;
  1425. name << fusion_str;
  1426. name << ggml_op_name(node->op) <<
  1427. " K=" << node->ne[0] <<
  1428. " (" << node->src[0]->ne[0] << "," << node->src[0]->ne[1] << "," << node->src[0]->ne[2] << "," << node->src[0]->ne[3] << ")";
  1429. timings[name.str()].push_back(time);
  1430. return;
  1431. }
  1432. timings[fusion_str + ggml_op_name(node->op)].push_back(time);
  1433. }
  1434. private:
  1435. std::map<std::string, std::vector<uint64_t>> timings;
  1436. std::map<std::string, std::vector<uint64_t>> flops;
  1437. uint32_t print_count {};
  1438. };
  1439. struct ggml_backend_vk_context {
  1440. std::string name;
  1441. vk_device device;
  1442. size_t semaphore_idx, event_idx;
  1443. ggml_vk_garbage_collector gc;
  1444. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1445. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging;
  1446. vk::Fence fence, almost_ready_fence;
  1447. bool submit_pending {};
  1448. bool almost_ready_fence_pending {};
  1449. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1450. // write partial sums to accumulate the square of the vector components
  1451. bool do_add_rms_partials_offset_calculation;
  1452. bool do_add_rms_partials;
  1453. uint64_t last_total_mul_mat_bytes {};
  1454. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1455. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1456. const ggml_tensor * prealloc_y_last_tensor_used {};
  1457. // Track which nodes have been used since the last sync, and whether they were written to
  1458. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1459. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1460. // Track which prealloc buffers have pending reads that need to be synchronized.
  1461. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1462. // and set to true after the buffer contents are consumed.
  1463. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1464. vk_context_ref compute_ctx;
  1465. vk_context_ref transfer_ctx;
  1466. std::vector<vk_context_ref> tensor_ctxs;
  1467. std::vector<vk::DescriptorPool> descriptor_pools;
  1468. std::vector<vk::DescriptorSet> descriptor_sets;
  1469. uint32_t descriptor_set_idx {};
  1470. uint32_t pipeline_descriptor_set_requirements {};
  1471. vk_command_pool compute_cmd_pool;
  1472. vk_command_pool transfer_cmd_pool;
  1473. // number of additional consecutive nodes that are being fused with the
  1474. // node currently being processed
  1475. int num_additional_fused_ops {};
  1476. // Bitmask of which fused ops need to write an intermediate value to memory.
  1477. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1478. // If there's no fusion, bit 0 is still set.
  1479. int fused_ops_write_mask {};
  1480. // for GGML_VK_PERF_LOGGER
  1481. std::unique_ptr<vk_perf_logger> perf_logger;
  1482. vk::QueryPool query_pool;
  1483. std::vector<const char *> query_fusion_names;
  1484. std::vector<ggml_tensor *> query_nodes;
  1485. int32_t num_queries {};
  1486. int32_t query_idx {};
  1487. };
  1488. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1489. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1490. if (tensor->view_src) {
  1491. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1492. }
  1493. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1494. }
  1495. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  1496. {
  1497. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  1498. }
  1499. template <typename T> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, T &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1500. GGML_UNUSED(p);
  1501. GGML_UNUSED(src0);
  1502. GGML_UNUSED(src1);
  1503. GGML_UNUSED(src2);
  1504. GGML_UNUSED(src3);
  1505. GGML_UNUSED(dst);
  1506. static_assert(!std::is_const<T>::value, "unexpected type");
  1507. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  1508. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  1509. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  1510. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  1511. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  1512. }
  1513. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_p021_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1514. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1515. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1516. p.b_offset = b_offset;
  1517. p.d_offset = d_offset;
  1518. GGML_UNUSED(src0);
  1519. GGML_UNUSED(src2);
  1520. GGML_UNUSED(src3);
  1521. }
  1522. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_nc_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1523. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1524. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1525. p.b_offset = b_offset;
  1526. p.d_offset = d_offset;
  1527. GGML_UNUSED(src0);
  1528. GGML_UNUSED(src2);
  1529. GGML_UNUSED(src3);
  1530. }
  1531. struct ggml_backend_vk_buffer_context {
  1532. vk_device_ref device;
  1533. vk_buffer dev_buffer;
  1534. std::string name;
  1535. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1536. device(device),
  1537. dev_buffer(dev_buffer),
  1538. name(name) {
  1539. }
  1540. ~ggml_backend_vk_buffer_context() {
  1541. ggml_vk_destroy_buffer(dev_buffer);
  1542. }
  1543. };
  1544. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1545. static std::mutex log_mutex;
  1546. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1547. std::lock_guard<std::mutex> guard(log_mutex);
  1548. vk_buffer buf = buf_ref.lock();
  1549. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1550. const std::string type = device ? "device" : "host";
  1551. allocations[buf->buffer] = size;
  1552. total_device += device ? size : 0;
  1553. total_host += device ? 0 : size;
  1554. 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));
  1555. }
  1556. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1557. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1558. return;
  1559. }
  1560. std::lock_guard<std::mutex> guard(log_mutex);
  1561. vk_buffer buf = buf_ref.lock();
  1562. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1563. std::string type = device ? "device" : "host";
  1564. auto it = allocations.find(buf->buffer);
  1565. total_device -= device ? it->second : 0;
  1566. total_host -= device ? 0 : it->second;
  1567. if (it != allocations.end()) {
  1568. 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));
  1569. allocations.erase(it);
  1570. } else {
  1571. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1572. }
  1573. }
  1574. #endif // GGML_VULKAN_MEMORY_DEBUG
  1575. struct vk_instance_t {
  1576. vk::Instance instance;
  1577. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1578. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1579. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1580. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1581. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1582. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1583. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1584. std::vector<size_t> device_indices;
  1585. std::vector<bool> device_supports_membudget;
  1586. vk_device devices[GGML_VK_MAX_DEVICES];
  1587. };
  1588. static bool vk_instance_initialized = false;
  1589. static vk_instance_t vk_instance;
  1590. #ifdef GGML_VULKAN_CHECK_RESULTS
  1591. static size_t vk_skip_checks;
  1592. static size_t vk_output_tensor;
  1593. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1594. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1595. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1596. #endif
  1597. 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);
  1598. static void ggml_backend_vk_free(ggml_backend_t backend);
  1599. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1600. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1601. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1602. return range;
  1603. }
  1604. // Wait for ctx->fence to be signaled.
  1605. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1606. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1607. // during this wait.
  1608. if (ctx->almost_ready_fence_pending) {
  1609. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1610. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1611. ctx->almost_ready_fence_pending = false;
  1612. }
  1613. // Spin (w/pause) waiting for the graph to finish executing.
  1614. vk::Result result;
  1615. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1616. if (result != vk::Result::eNotReady) {
  1617. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1618. exit(1);
  1619. }
  1620. for (uint32_t i = 0; i < 100; ++i) {
  1621. YIELD();
  1622. YIELD();
  1623. YIELD();
  1624. YIELD();
  1625. YIELD();
  1626. YIELD();
  1627. YIELD();
  1628. YIELD();
  1629. YIELD();
  1630. YIELD();
  1631. }
  1632. }
  1633. ctx->device->device.resetFences({ ctx->fence });
  1634. }
  1635. // variables to track number of compiles in progress
  1636. static uint32_t compile_count = 0;
  1637. static std::mutex compile_count_mutex;
  1638. static std::condition_variable compile_count_cond;
  1639. static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, size_t spv_size, const void* spv_data, const std::string entrypoint,
  1640. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1641. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1642. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1643. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1644. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1645. GGML_ASSERT(parameter_count > 0);
  1646. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1647. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1648. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1649. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1650. vk::PushConstantRange pcr(
  1651. vk::ShaderStageFlagBits::eCompute,
  1652. 0,
  1653. pipeline->push_constant_size
  1654. );
  1655. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1656. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1657. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1658. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1659. specialization_entries[i].constantID = i;
  1660. specialization_entries[i].offset = i * sizeof(uint32_t);
  1661. specialization_entries[i].size = sizeof(uint32_t);
  1662. }
  1663. vk::SpecializationInfo specialization_info(
  1664. specialization_entries.size(),
  1665. specialization_entries.data(),
  1666. specialization_constants.size() * sizeof(uint32_t),
  1667. specialization_constants.data()
  1668. );
  1669. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1670. if (device->subgroup_require_full_support && require_full_subgroups) {
  1671. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1672. }
  1673. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1674. pipeline_shader_stage_create_flags,
  1675. vk::ShaderStageFlagBits::eCompute,
  1676. pipeline->shader_module,
  1677. entrypoint.c_str(),
  1678. &specialization_info);
  1679. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1680. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1681. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1682. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1683. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1684. }
  1685. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1686. device->pipeline_executable_properties_support ?
  1687. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1688. vk::PipelineCreateFlags{},
  1689. pipeline_shader_create_info,
  1690. pipeline->layout);
  1691. vk::PipelineRobustnessCreateInfoEXT rci;
  1692. if (device->pipeline_robustness && disable_robustness) {
  1693. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1694. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1695. compute_pipeline_create_info.setPNext(&rci);
  1696. }
  1697. try {
  1698. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1699. } catch (const vk::SystemError& e) {
  1700. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1701. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1702. throw e;
  1703. }
  1704. pipeline->compiled = true;
  1705. if (vk_instance.debug_utils_support) {
  1706. vk::DebugUtilsObjectNameInfoEXT duoni;
  1707. duoni.objectType = vk::ObjectType::ePipeline;
  1708. duoni.pObjectName = pipeline->name.c_str();
  1709. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1710. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1711. }
  1712. if (device->pipeline_executable_properties_support) {
  1713. vk::PipelineExecutableInfoKHR executableInfo;
  1714. executableInfo.pipeline = pipeline->pipeline;
  1715. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1716. for (auto & s : statistics) {
  1717. // "Register Count" is reported by NVIDIA drivers.
  1718. if (strcmp(s.name, "Register Count") == 0) {
  1719. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1720. pipeline->register_count = (uint32_t)s.value.u64;
  1721. }
  1722. }
  1723. }
  1724. device->all_pipelines.push_back(pipeline);
  1725. {
  1726. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1727. assert(compile_count > 0);
  1728. compile_count--;
  1729. }
  1730. compile_count_cond.notify_all();
  1731. }
  1732. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1733. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1734. device.destroyPipelineLayout(pipeline->layout);
  1735. device.destroyShaderModule(pipeline->shader_module);
  1736. device.destroyPipeline(pipeline->pipeline);
  1737. }
  1738. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1739. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1740. ctx->pipeline_descriptor_set_requirements += n;
  1741. if (!pipeline->compiled) {
  1742. pipeline->needed = true;
  1743. ggml_vk_load_shaders(ctx->device);
  1744. }
  1745. ggml_pipeline_allocate_descriptor_sets(ctx);
  1746. }
  1747. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1748. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1749. // Enough descriptors are available
  1750. return;
  1751. }
  1752. vk_device& device = ctx->device;
  1753. // Grow by 50% to avoid frequent allocations
  1754. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1755. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1756. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1757. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1758. while (to_alloc > 0) {
  1759. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1760. to_alloc -= alloc_count;
  1761. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1762. if (pool_idx >= ctx->descriptor_pools.size()) {
  1763. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1764. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1765. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1766. }
  1767. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1768. for (uint32_t i = 0; i < alloc_count; i++) {
  1769. layouts[i] = device->dsl;
  1770. }
  1771. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1772. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1773. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1774. pool_idx++;
  1775. }
  1776. }
  1777. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1778. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1779. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1780. // Reuse command buffer
  1781. return p.cmd_buffers[p.cmd_buffer_idx++];
  1782. }
  1783. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1784. p.pool,
  1785. vk::CommandBufferLevel::ePrimary,
  1786. 1);
  1787. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1788. auto buf = cmd_buffers.front();
  1789. p.cmd_buffers.push_back(buf);
  1790. p.cmd_buffer_idx++;
  1791. return buf;
  1792. }
  1793. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1794. if (ctx->seqs.empty()) {
  1795. if (fence) {
  1796. std::lock_guard<std::mutex> guard(queue_mutex);
  1797. ctx->p->q->queue.submit({}, fence);
  1798. }
  1799. return;
  1800. }
  1801. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1802. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1803. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1804. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1805. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1806. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1807. std::vector<vk::SubmitInfo> submit_infos;
  1808. int idx = -1;
  1809. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1810. size_t reserve = 0;
  1811. for (const auto& sequence : ctx->seqs) {
  1812. reserve += sequence.size();
  1813. }
  1814. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1815. tl_wait_semaphores.reserve(reserve);
  1816. tl_wait_vals.reserve(reserve);
  1817. tl_signal_semaphores.reserve(reserve);
  1818. tl_signal_vals.reserve(reserve);
  1819. tl_submit_infos.reserve(reserve);
  1820. submit_infos.reserve(reserve);
  1821. stage_flags.reserve(reserve);
  1822. for (const auto& sequence : ctx->seqs) {
  1823. for (const auto& submission : sequence) {
  1824. stage_flags.push_back({});
  1825. idx++;
  1826. tl_wait_vals.push_back({});
  1827. tl_wait_semaphores.push_back({});
  1828. tl_signal_vals.push_back({});
  1829. tl_signal_semaphores.push_back({});
  1830. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1831. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1832. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1833. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1834. }
  1835. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1836. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1837. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1838. }
  1839. tl_submit_infos.push_back({
  1840. (uint32_t) submission.wait_semaphores.size(),
  1841. tl_wait_vals[idx].data(),
  1842. (uint32_t) submission.signal_semaphores.size(),
  1843. tl_signal_vals[idx].data(),
  1844. });
  1845. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1846. tl_submit_infos[idx].pNext = nullptr;
  1847. vk::SubmitInfo si{
  1848. (uint32_t) submission.wait_semaphores.size(),
  1849. tl_wait_semaphores[idx].data(),
  1850. stage_flags[idx].data(),
  1851. 1,
  1852. &submission.buffer,
  1853. (uint32_t) submission.signal_semaphores.size(),
  1854. tl_signal_semaphores[idx].data(),
  1855. };
  1856. si.setPNext(&tl_submit_infos[idx]);
  1857. submit_infos.push_back(si);
  1858. }
  1859. }
  1860. std::lock_guard<std::mutex> guard(queue_mutex);
  1861. ctx->p->q->queue.submit(submit_infos, fence);
  1862. ctx->seqs.clear();
  1863. }
  1864. 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) {
  1865. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1866. const uint32_t qfsize = queue_family_props.size();
  1867. // Try with avoid preferences first
  1868. for (uint32_t i = 0; i < qfsize; i++) {
  1869. 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)) {
  1870. return i;
  1871. }
  1872. }
  1873. // Fall back to only required
  1874. for (size_t i = 0; i < qfsize; i++) {
  1875. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1876. return i;
  1877. }
  1878. }
  1879. // Fall back to reusing compute queue
  1880. for (size_t i = 0; i < qfsize; i++) {
  1881. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1882. return i;
  1883. }
  1884. }
  1885. // Fall back to ignoring min_num_queries
  1886. for (size_t i = 0; i < qfsize; i++) {
  1887. if (queue_family_props[i].queueFlags & required) {
  1888. return i;
  1889. }
  1890. }
  1891. // 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.
  1892. // 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.
  1893. if (compute_index >= 0) {
  1894. return compute_index;
  1895. }
  1896. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1897. for(auto &q_family : queue_family_props) {
  1898. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1899. }
  1900. abort();
  1901. }
  1902. 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) {
  1903. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1904. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1905. q.queue_family_index = queue_family_index;
  1906. q.transfer_only = transfer_only;
  1907. q.cmd_pool.init(device, &q);
  1908. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1909. q.stage_flags = stage_flags;
  1910. }
  1911. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1912. vk_context result = std::make_shared<vk_context_struct>();
  1913. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1914. ctx->gc.contexts.emplace_back(result);
  1915. result->p = &p;
  1916. return result;
  1917. }
  1918. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1919. vk_context result = std::make_shared<vk_context_struct>();
  1920. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1921. result->p = &p;
  1922. return result;
  1923. }
  1924. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1925. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1926. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1927. vk::SemaphoreCreateInfo ci{};
  1928. ci.setPNext(&tci);
  1929. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1930. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1931. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1932. }
  1933. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1934. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1935. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1936. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1937. vk::SemaphoreCreateInfo ci{};
  1938. ci.setPNext(&tci);
  1939. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1940. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1941. }
  1942. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1943. }
  1944. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1945. if (ctx->event_idx >= ctx->gc.events.size()) {
  1946. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1947. }
  1948. return ctx->gc.events[ctx->event_idx++];
  1949. }
  1950. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1951. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1952. // Requires command buffers to be done
  1953. device->device.resetCommandPool(p.pool);
  1954. p.cmd_buffer_idx = 0;
  1955. }
  1956. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1957. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1958. // Arbitrary frequency to cleanup/reuse command buffers
  1959. static constexpr uint32_t cleanup_frequency = 10;
  1960. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1961. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1962. }
  1963. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1964. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1965. }
  1966. }
  1967. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1968. std::vector<uint32_t> indices;
  1969. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1970. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1971. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1972. (flags & memory_type.propertyFlags) == flags &&
  1973. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1974. indices.push_back(i);
  1975. }
  1976. }
  1977. return indices;
  1978. }
  1979. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1980. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags_list.begin()[0]) << ", " << to_string(req_flags_list.begin()[req_flags_list.size()-1]) << ")");
  1981. if (size > device->max_buffer_size) {
  1982. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  1983. }
  1984. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1985. if (size == 0) {
  1986. buf->size = 0;
  1987. return buf;
  1988. }
  1989. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1990. vk::MemoryAllocateFlags mem_flags {};
  1991. if (device->buffer_device_address) {
  1992. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1993. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1994. }
  1995. vk::BufferCreateInfo buffer_create_info{
  1996. vk::BufferCreateFlags(),
  1997. size,
  1998. usage_flags,
  1999. vk::SharingMode::eExclusive,
  2000. 0,
  2001. nullptr,
  2002. };
  2003. buf->buffer = device->device.createBuffer(buffer_create_info);
  2004. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  2005. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2006. const vk::MemoryPriorityAllocateInfoEXT mem_priority_info { 1.0f };
  2007. vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  2008. if (device->memory_priority) {
  2009. mem_flags_info.setPNext(&mem_priority_info);
  2010. }
  2011. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  2012. const auto & req_flags = *it;
  2013. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  2014. if (memory_type_indices.empty()) {
  2015. continue;
  2016. }
  2017. buf->memory_property_flags = req_flags;
  2018. bool done = false;
  2019. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  2020. try {
  2021. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  2022. done = true;
  2023. break;
  2024. } catch (const vk::SystemError& e) {
  2025. // loop and retry
  2026. // during last attempt throw the exception
  2027. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  2028. device->device.destroyBuffer(buf->buffer);
  2029. throw e;
  2030. }
  2031. }
  2032. }
  2033. if (done) {
  2034. break;
  2035. }
  2036. }
  2037. if (!buf->device_memory) {
  2038. device->device.destroyBuffer(buf->buffer);
  2039. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  2040. }
  2041. buf->ptr = nullptr;
  2042. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2043. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  2044. }
  2045. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  2046. buf->device = device;
  2047. buf->size = size;
  2048. if (device->buffer_device_address) {
  2049. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  2050. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  2051. }
  2052. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2053. device->memory_logger->log_allocation(buf, size);
  2054. #endif
  2055. return buf;
  2056. }
  2057. 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)) {
  2058. try {
  2059. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  2060. } catch (const vk::SystemError& e) {
  2061. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  2062. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2063. throw e;
  2064. }
  2065. }
  2066. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  2067. vk_buffer buf;
  2068. try {
  2069. if (device->prefer_host_memory) {
  2070. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2071. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2072. } else if (device->uma) {
  2073. // Fall back to host memory type
  2074. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2075. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2076. } else if (device->disable_host_visible_vidmem) {
  2077. if (device->allow_sysmem_fallback) {
  2078. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2079. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2080. } else {
  2081. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  2082. }
  2083. } else {
  2084. // use rebar if available, otherwise fallback to device only visible memory
  2085. if (device->allow_sysmem_fallback) {
  2086. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2087. vk::MemoryPropertyFlagBits::eDeviceLocal,
  2088. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2089. } else {
  2090. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2091. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2092. }
  2093. }
  2094. } catch (const vk::SystemError& e) {
  2095. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  2096. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2097. throw e;
  2098. }
  2099. return buf;
  2100. }
  2101. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  2102. if (buf == nullptr) {
  2103. return;
  2104. }
  2105. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2106. if (buf->device != nullptr) {
  2107. buf->device->memory_logger->log_deallocation(buf);
  2108. }
  2109. #endif
  2110. buf.reset();
  2111. }
  2112. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  2113. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  2114. }
  2115. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  2116. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  2117. const bool transfer_queue = subctx->p->q->transfer_only;
  2118. if (ctx) {
  2119. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  2120. }
  2121. subctx->s->buffer.pipelineBarrier(
  2122. subctx->p->q->stage_flags,
  2123. subctx->p->q->stage_flags,
  2124. {},
  2125. { {
  2126. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  2127. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  2128. } },
  2129. {},
  2130. {}
  2131. );
  2132. }
  2133. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  2134. VK_LOG_DEBUG("ggml_vk_wait_events()");
  2135. if (events.empty()) {
  2136. return;
  2137. }
  2138. ctx->s->buffer.waitEvents(
  2139. events,
  2140. ctx->p->q->stage_flags,
  2141. ctx->p->q->stage_flags,
  2142. {},
  2143. {},
  2144. {}
  2145. );
  2146. }
  2147. // number of rows/cols for flash attention shader
  2148. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2149. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2150. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsk, uint32_t hsv) {
  2151. if (hsv >= 192) {
  2152. return 2;
  2153. } else if ((hsv | hsk) & 8) {
  2154. return 4;
  2155. } else {
  2156. return 8;
  2157. }
  2158. }
  2159. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2160. // 128 threads split into four subgroups, each subgroup does 1/4
  2161. // of the Bc dimension.
  2162. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2163. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2164. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2165. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2166. if (path == FA_COOPMAT2) {
  2167. return flash_attention_num_small_rows;
  2168. } else {
  2169. return scalar_flash_attention_num_small_rows;
  2170. }
  2171. }
  2172. static std::array<uint32_t, 2> fa_rows_cols(FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) {
  2173. GGML_UNUSED(clamp);
  2174. GGML_UNUSED(hsv);
  2175. if (path == FA_SCALAR) {
  2176. if (small_rows) {
  2177. return {scalar_flash_attention_num_small_rows, 64};
  2178. } else {
  2179. if ((hsv | hsk) & 8) {
  2180. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2181. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2182. return {get_fa_scalar_num_large_rows(hsk, hsv), 64};
  2183. } else {
  2184. return {get_fa_scalar_num_large_rows(hsk, hsv), 32};
  2185. }
  2186. }
  2187. }
  2188. if (path == FA_COOPMAT1) {
  2189. if (small_rows) {
  2190. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2191. } else {
  2192. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2193. }
  2194. }
  2195. // small rows, large cols
  2196. if (small_rows) {
  2197. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2198. }
  2199. // small cols to reduce register count
  2200. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2201. if (hsk >= 512 || hsv >= 512) {
  2202. return {32, 32};
  2203. } else {
  2204. return {64, 32};
  2205. }
  2206. }
  2207. return {64, 64};
  2208. }
  2209. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  2210. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  2211. }
  2212. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id, ggml_type src0_type) {
  2213. uint32_t lut_size = 0;
  2214. switch (src0_type) {
  2215. case GGML_TYPE_IQ1_S:
  2216. case GGML_TYPE_IQ1_M:
  2217. lut_size = 2*2048;
  2218. break;
  2219. case GGML_TYPE_IQ2_XXS:
  2220. lut_size = 8*256;
  2221. break;
  2222. case GGML_TYPE_IQ2_XS:
  2223. lut_size = 8*512;
  2224. break;
  2225. case GGML_TYPE_IQ2_S:
  2226. lut_size = 8*1024;
  2227. break;
  2228. case GGML_TYPE_IQ3_XXS:
  2229. lut_size = 4*256;
  2230. break;
  2231. case GGML_TYPE_IQ3_S:
  2232. lut_size = 4*512;
  2233. break;
  2234. case GGML_TYPE_IQ4_NL:
  2235. case GGML_TYPE_IQ4_XS:
  2236. case GGML_TYPE_MXFP4:
  2237. lut_size = 4*16;
  2238. break;
  2239. default:
  2240. break;
  2241. }
  2242. // Needs to be kept up to date on shader changes
  2243. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2244. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2245. const uint32_t warps = warptile[0] / warptile[10];
  2246. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2247. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2248. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2249. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2250. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2251. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2252. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2253. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2254. return supported;
  2255. }
  2256. struct GpuPipelineConfig {
  2257. // GPU architecture identifier.
  2258. // Example: vk_device_architecture::AMD_GCN
  2259. vk_device_architecture arch;
  2260. // Mapping of pipeline names to their specific subgroup sizes.
  2261. // Example: {"soft_max_f32", 64}
  2262. std::unordered_map<std::string, uint32_t> pipelines;
  2263. // Default subgroup size for this GPU.
  2264. // Defaults to 0 if not explicitly provided.
  2265. uint32_t default_subgroup_size = 0;
  2266. };
  2267. // Pipeline configuration for RDNA1 GPUs.
  2268. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2269. {"soft_max", 64}, {"im2col", 64},
  2270. {"argmax", 64}, {"mul_mat_vec", 64},
  2271. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2272. };
  2273. // Pipeline configuration for RDNA2 GPUs.
  2274. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2275. {"soft_max", 64}, {"im2col", 64},
  2276. };
  2277. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2278. // Define configurations for different GPUs.
  2279. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2280. {
  2281. vk_device_architecture::AMD_RDNA1,
  2282. {
  2283. rdna1_pipelines,
  2284. },
  2285. RDNA_DEFAULT_SUBGROUP_SIZE
  2286. },
  2287. {
  2288. vk_device_architecture::AMD_RDNA2,
  2289. {
  2290. rdna2_pipelines,
  2291. },
  2292. RDNA_DEFAULT_SUBGROUP_SIZE
  2293. },
  2294. };
  2295. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2296. for (const auto &config : gpu_pipeline_configs) {
  2297. if (config.arch == arch) {
  2298. auto pipIt = config.pipelines.find(pipeline_name);
  2299. if (pipIt != config.pipelines.end()) {
  2300. return pipIt->second;
  2301. }
  2302. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2303. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2304. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2305. for (const auto &entry : sorted_pipelines) {
  2306. if (pipeline_name.find(entry.first) != std::string::npos) {
  2307. return entry.second;
  2308. }
  2309. }
  2310. return config.default_subgroup_size;
  2311. }
  2312. }
  2313. return 0; // If no matching configuration is found
  2314. }
  2315. static void ggml_vk_load_shaders(vk_device& device) {
  2316. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2317. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2318. // some shaders have a minimum subgroup size
  2319. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2320. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2321. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2322. const uint32_t mul_mat_subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2323. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2324. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2325. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2326. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2327. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2328. // mulmat
  2329. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2330. l_warptile_id, m_warptile_id, s_warptile_id,
  2331. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2332. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2333. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2334. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2335. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2336. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2337. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2338. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2339. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2340. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2341. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2342. uint32_t l_align, m_align, s_align;
  2343. if (device->coopmat2) {
  2344. // spec constants and tile sizes for non-quant matmul/matmul_id
  2345. l_warptile = { 256, 128, 256, 64, 1 };
  2346. m_warptile = { 256, 128, 128, 64, 0 };
  2347. s_warptile = { 128, 64, 64, 64, 0 };
  2348. l_wg_denoms = {128, 256, 1 };
  2349. m_wg_denoms = {128, 128, 1 };
  2350. s_wg_denoms = { 64, 64, 1 };
  2351. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2352. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2353. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2354. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2355. l_mmq_wg_denoms = { 128, 256, 1 };
  2356. m_mmq_wg_denoms = { 128, 128, 1 };
  2357. s_mmq_wg_denoms = { 32, 64, 1 };
  2358. // spec constants and tile sizes for quant matmul (Qi_K)
  2359. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2360. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2361. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2362. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2363. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2364. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2365. // spec constants and tile sizes for quant matmul_id
  2366. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2367. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2368. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2369. l_mmqid_wg_denoms = { 128, 128, 1 };
  2370. m_mmqid_wg_denoms = { 128, 64, 1 };
  2371. s_mmqid_wg_denoms = { 128, 64, 1 };
  2372. l_align = 128;
  2373. m_align = 64;
  2374. s_align = 32;
  2375. } else {
  2376. // Matrix cores require different warp group sizes
  2377. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2378. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2379. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2380. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2381. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2382. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2383. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2384. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2385. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2386. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2387. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2388. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2389. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2390. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2391. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2392. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2393. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2394. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2395. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2396. // K-quants use even more registers, mitigate by setting WMITER to 1
  2397. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2398. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2399. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2400. l_warptile_id = { 128, 128, 128, 16, mul_mat_subgroup_size_16 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_16 };
  2401. m_warptile_id = { 128, 64, 64, 16, mul_mat_subgroup_size_16, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_16 };
  2402. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2403. l_warptile_mmqid = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_8 };
  2404. m_warptile_mmqid = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_8 };
  2405. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2406. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2407. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2408. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2409. l_warptile_mmqid_int_k = { 128, 128, 128, 32, mul_mat_subgroup_size_16 * 2, 64, 1, 4, 4, 1, mul_mat_subgroup_size_16 };
  2410. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2411. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2412. // chip specific tuning
  2413. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2414. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2415. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2416. }
  2417. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2418. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2419. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2420. l_align = 128;
  2421. m_align = 64;
  2422. s_align = 32;
  2423. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2424. ggml_type t = (ggml_type)i;
  2425. // Disable medium and large matrix multiplication if not enough shared memory is available
  2426. // Check mmq warptiles as the largest configuration
  2427. // Throw an error if not enough for any matrix multiplication is available
  2428. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2429. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2430. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2431. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2432. device->mul_mat_m[i] = false;
  2433. device->mul_mat_l[i] = false;
  2434. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2435. device->mul_mat_l[i] = false;
  2436. }
  2437. // Disable mul_mat_id if not enough shared memory is available
  2438. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2439. device->mul_mat_id_s[i] = false;
  2440. device->mul_mat_id_m[i] = false;
  2441. device->mul_mat_id_l[i] = false;
  2442. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2443. device->mul_mat_id_m[i] = false;
  2444. device->mul_mat_id_l[i] = false;
  2445. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2446. device->mul_mat_id_l[i] = false;
  2447. }
  2448. }
  2449. }
  2450. if (!device->pipeline_matmul_f32) {
  2451. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2452. }
  2453. if (!device->pipeline_matmul_f32_f16) {
  2454. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2455. }
  2456. if (!device->pipeline_matmul_id_f32) {
  2457. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2458. }
  2459. if (!device->pipeline_matmul_bf16) {
  2460. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2461. }
  2462. if (!device->pipeline_matmul_id_bf16) {
  2463. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2464. }
  2465. std::vector<std::future<void>> compiles;
  2466. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const char *name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2467. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2468. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2469. if (!require_full_subgroups && required_subgroup_size == 0) {
  2470. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2471. }
  2472. if (!pipeline) {
  2473. pipeline = std::make_shared<vk_pipeline_struct>();
  2474. }
  2475. if (!pipeline->initialized) {
  2476. pipeline->name = name;
  2477. pipeline->parameter_count = parameter_count;
  2478. pipeline->push_constant_size = push_constant_size;
  2479. pipeline->wg_denoms = wg_denoms;
  2480. pipeline->align = align;
  2481. pipeline->initialized = true;
  2482. }
  2483. if (!pipeline->needed || pipeline->compiled) {
  2484. return;
  2485. }
  2486. // TODO: We're no longer benefitting from the async compiles (shaders are
  2487. // compiled individually, as needed) and this complexity can be removed.
  2488. {
  2489. // wait until fewer than N compiles are in progress
  2490. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2491. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2492. while (compile_count >= N) {
  2493. compile_count_cond.wait(guard);
  2494. }
  2495. compile_count++;
  2496. }
  2497. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2498. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2499. };
  2500. auto const &ggml_vk_create_pipeline2 = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2501. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2502. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2503. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2504. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2505. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2506. };
  2507. auto const &fa_wg_denoms = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  2508. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2509. };
  2510. auto const &fa_spec_constants = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  2511. // For large number of rows, 128 invocations seems to work best.
  2512. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2513. // can't use 256 for D==80.
  2514. // For scalar, use 128 (arbitrary)
  2515. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2516. const uint32_t D = (hsk|hsv);
  2517. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2518. ? scalar_flash_attention_workgroup_size
  2519. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2520. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2521. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2522. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2523. const uint32_t D_lsb = D ^ (D & (D-1));
  2524. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2525. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2526. };
  2527. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2528. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2529. uint32_t HSK = fa.first.HSK; \
  2530. uint32_t HSV = fa.first.HSV; \
  2531. bool small_rows = fa.first.small_rows; \
  2532. FaCodePath path = fa.first.path; \
  2533. bool aligned = fa.first.aligned; \
  2534. bool f32acc = fa.first.f32acc; \
  2535. if (path == FAPATH) { \
  2536. if (aligned) { \
  2537. if (f32acc) { \
  2538. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2539. } else { \
  2540. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2541. } \
  2542. } else { \
  2543. if (f32acc) { \
  2544. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2545. } else { \
  2546. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2547. } \
  2548. } \
  2549. } \
  2550. }
  2551. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2552. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2553. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2554. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2555. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2556. if (device->coopmat1_fa_support) {
  2557. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2558. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2559. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2560. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2561. }
  2562. #endif
  2563. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2564. if (device->coopmat2) {
  2565. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2566. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2567. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2568. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2569. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2570. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2571. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2572. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2573. }
  2574. #endif
  2575. #undef CREATE_FA
  2576. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2577. if (device->coopmat2) {
  2578. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2579. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2580. 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); \
  2581. 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); \
  2582. 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); \
  2583. 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); \
  2584. 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); \
  2585. 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); \
  2586. // Create 2 variants, {f16,f32} accumulator
  2587. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2588. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2589. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2590. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2591. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2592. if (device->coopmat_bf16_support) {
  2593. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2594. }
  2595. #endif
  2596. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0], matmul_q4_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2597. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1], matmul_q4_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2598. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0], matmul_q5_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2599. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1], matmul_q5_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2600. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0], matmul_q8_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2601. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K], matmul_q2_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2602. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K], matmul_q3_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2603. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K], matmul_q4_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2604. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K], matmul_q5_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2605. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K], matmul_q6_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2606. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_S], matmul_iq1_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2607. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_M], matmul_iq1_m_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2608. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2609. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2610. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_S], matmul_iq2_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2611. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2612. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_S], matmul_iq3_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2613. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2614. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2615. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_MXFP4], matmul_mxfp4_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2616. GGML_ASSERT(device->subgroup_ballot);
  2617. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2618. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2619. if (device->coopmat_bf16_support) {
  2620. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2621. }
  2622. #endif
  2623. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2624. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2625. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2626. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2627. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2628. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2629. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2630. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2631. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2632. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2633. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2634. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2635. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2636. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2637. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2638. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2639. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2640. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2641. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2642. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2643. #undef CREATE_MM
  2644. #undef CREATE_MM2
  2645. } else
  2646. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2647. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2648. if (device->coopmat_support) {
  2649. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2650. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2651. if (device->mul_mat ## ID ## _l[TYPE]) \
  2652. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, true); \
  2653. if (device->mul_mat ## ID ## _m[TYPE]) \
  2654. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, true); \
  2655. if (device->mul_mat ## ID ## _s[TYPE]) \
  2656. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, true); \
  2657. if (device->mul_mat ## ID ## _l[TYPE]) \
  2658. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, true); \
  2659. if (device->mul_mat ## ID ## _m[TYPE]) \
  2660. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, true); \
  2661. if (device->mul_mat ## ID ## _s[TYPE]) \
  2662. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, true); \
  2663. // Create 2 variants, {f16,f32} accumulator
  2664. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2665. if (device->coopmat_acc_f16_support) { \
  2666. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2667. } \
  2668. if (device->coopmat_acc_f32_support) { \
  2669. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2670. } \
  2671. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2672. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2673. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2674. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2675. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2676. if (device->coopmat_bf16_support) {
  2677. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2678. }
  2679. #endif
  2680. if (device->coopmat_acc_f16_support) {
  2681. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2682. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2683. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2684. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2685. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2686. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2687. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2688. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2689. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2690. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2691. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2692. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2693. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2694. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2695. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2696. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2697. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2698. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2699. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2700. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2701. } else {
  2702. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2703. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2704. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2705. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2706. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2707. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2708. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2709. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2710. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2711. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2712. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2713. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2714. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2715. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2716. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2717. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2718. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2719. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2720. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2721. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2722. }
  2723. GGML_ASSERT(device->subgroup_ballot);
  2724. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2725. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2726. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2727. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2728. if (device->coopmat_bf16_support) {
  2729. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2730. }
  2731. #endif
  2732. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2733. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2734. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2735. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2736. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2737. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2738. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2739. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2740. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2741. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2742. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2743. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2744. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2745. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2746. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2747. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2748. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2749. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2750. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2751. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2752. #undef CREATE_MM2
  2753. #undef CREATE_MM
  2754. } else
  2755. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2756. if (device->fp16) {
  2757. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2758. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2759. if (device->mul_mat ## ID ## _l[TYPE]) \
  2760. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2761. if (device->mul_mat ## ID ## _m[TYPE]) \
  2762. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2763. if (device->mul_mat ## ID ## _s[TYPE]) \
  2764. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2765. if (device->mul_mat ## ID ## _l[TYPE]) \
  2766. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2767. if (device->mul_mat ## ID ## _m[TYPE]) \
  2768. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2769. if (device->mul_mat ## ID ## _s[TYPE]) \
  2770. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2771. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2772. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2773. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->l, #NAMELC "_l", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2774. } \
  2775. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2776. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->m, #NAMELC "_m", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2777. } \
  2778. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2779. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->s, #NAMELC "_s", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2780. } \
  2781. // Create 2 variants, {f16,f32} accumulator
  2782. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2783. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2784. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2785. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2786. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2787. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2788. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2789. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2790. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2791. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2792. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2793. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2794. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2795. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2796. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2797. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2798. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2799. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2800. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2801. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2802. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2803. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2804. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2805. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2806. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2807. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2808. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2809. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2810. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2811. if (device->integer_dot_product) {
  2812. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0], matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2813. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1], matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2814. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0], matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2815. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1], matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2816. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0], matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2817. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_MXFP4], matmul_mxfp4_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2818. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K], matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2819. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K], matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2820. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K], matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2821. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K], matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2822. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K], matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2823. }
  2824. #endif
  2825. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2826. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2827. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2828. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2829. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2830. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2831. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2832. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2833. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2834. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2835. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2836. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2837. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2838. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2839. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2840. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2841. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2842. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2843. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2844. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2845. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2846. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2847. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2848. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2849. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2850. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2851. if (device->integer_dot_product) {
  2852. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2853. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2854. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2855. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2856. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2857. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2858. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2859. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2860. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2861. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2862. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2863. }
  2864. #endif
  2865. } else {
  2866. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2867. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2868. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2869. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2870. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2871. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2872. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2873. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2874. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2875. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2876. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2877. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2878. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2879. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2880. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2881. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2882. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2883. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2884. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2885. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2886. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2887. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2888. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2889. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2890. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2891. if (device->integer_dot_product) {
  2892. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2893. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2894. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2895. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2896. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2897. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2898. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2899. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2900. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2901. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2902. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2903. }
  2904. #endif
  2905. }
  2906. #undef CREATE_MM2
  2907. #undef CREATE_MMQ
  2908. #undef CREATE_MM
  2909. } else {
  2910. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2911. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2912. if (device->mul_mat ## ID ## _l[TYPE]) \
  2913. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2914. if (device->mul_mat ## ID ## _m[TYPE]) \
  2915. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2916. if (device->mul_mat ## ID ## _s[TYPE]) \
  2917. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2918. if (device->mul_mat ## ID ## _l[TYPE]) \
  2919. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2920. if (device->mul_mat ## ID ## _m[TYPE]) \
  2921. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2922. if (device->mul_mat ## ID ## _s[TYPE]) \
  2923. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2924. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2925. if (device->mul_mat ## ID ## _l[TYPE]) \
  2926. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC "_l", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  2927. if (device->mul_mat ## ID ## _m[TYPE]) \
  2928. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC "_m", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  2929. if (device->mul_mat ## ID ## _s[TYPE]) \
  2930. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC "_s", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  2931. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2932. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2933. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2934. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2935. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2936. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2937. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2938. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2939. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2940. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2941. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2942. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2943. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2944. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2945. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2946. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2947. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2948. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2949. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2950. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2951. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2952. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2953. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2954. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2955. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2956. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2957. if (device->integer_dot_product) {
  2958. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2959. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2960. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2961. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2962. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2963. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2964. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2965. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2966. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2967. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2968. }
  2969. #endif
  2970. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2971. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2972. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2973. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2974. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2975. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_subgroup_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2976. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_subgroup_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2977. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_subgroup_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2978. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_subgroup_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2979. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_subgroup_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2980. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_subgroup_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2981. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_subgroup_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2982. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_subgroup_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2983. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_subgroup_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2984. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_subgroup_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2985. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_subgroup_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2986. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_subgroup_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2987. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_subgroup_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2988. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_subgroup_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2989. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_subgroup_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2990. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_subgroup_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2991. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_subgroup_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2992. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_subgroup_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2993. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_subgroup_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2994. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_subgroup_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2995. } else {
  2996. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2997. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2998. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2999. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  3000. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3001. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3002. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3003. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3004. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3005. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3006. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3007. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3008. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3009. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3010. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3011. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3012. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3013. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3014. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3015. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3016. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3017. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3018. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3019. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3020. }
  3021. }
  3022. // reusing CREATE_MM from the fp32 path
  3023. if ((device->coopmat2 || device->coopmat_support)
  3024. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3025. && !device->coopmat_bf16_support
  3026. #endif
  3027. ) {
  3028. // use scalar tile sizes
  3029. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  3030. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  3031. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  3032. l_wg_denoms = {128, 128, 1 };
  3033. m_wg_denoms = { 64, 64, 1 };
  3034. s_wg_denoms = { 32, 32, 1 };
  3035. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3036. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  3037. }
  3038. #undef CREATE_MM
  3039. // mul mat vec
  3040. // the number of rows computed per shader depends on GPU model and quant
  3041. uint32_t rm_stdq = 1;
  3042. uint32_t rm_kq = 2;
  3043. uint32_t rm_stdq_int = 1;
  3044. uint32_t rm_kq_int = 1;
  3045. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3046. if (device->architecture == AMD_GCN) {
  3047. rm_stdq = 2;
  3048. rm_kq = 4;
  3049. rm_stdq_int = 4;
  3050. }
  3051. } else if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3052. rm_stdq = 2;
  3053. rm_stdq_int = 2;
  3054. }
  3055. uint32_t rm_iq = 2 * rm_kq;
  3056. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  3057. // Ensure a subgroup size >= 16 is available
  3058. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  3059. const uint32_t subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control && device->subgroup_min_size <= 16 && device->subgroup_max_size >= 16) ? 16 : device->subgroup_size;
  3060. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  3061. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  3062. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  3063. static constexpr uint32_t mul_mat_vec_num_bindings = 5;
  3064. static constexpr uint32_t mul_mat_vec_id_num_bindings = 6;
  3065. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  3066. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  3067. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  3068. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3069. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3070. SHADER_REDUCTION_MODE_SHMEM;
  3071. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3072. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3073. SHADER_REDUCTION_MODE_SHMEM;
  3074. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  3075. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3076. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3077. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3078. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3079. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3080. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3081. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3082. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3083. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3084. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3085. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3086. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3087. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3088. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3089. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3090. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3091. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3092. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3093. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3094. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3095. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3096. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3097. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", arr_dmmv_mxfp4_f32_f32_len[reduc16], arr_dmmv_mxfp4_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3098. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3099. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3100. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3101. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3102. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3103. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3104. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3105. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3106. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3107. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3108. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3109. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3110. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3111. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3112. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3113. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3114. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3115. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3116. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3117. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3118. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3119. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3120. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", arr_dmmv_mxfp4_f16_f32_len[reduc16], arr_dmmv_mxfp4_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3121. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3122. if (device->integer_dot_product) {
  3123. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3124. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3125. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3126. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3127. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3128. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3129. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3130. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3131. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3132. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3133. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3134. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3135. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3136. }
  3137. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3138. }
  3139. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", arr_dmmv_id_f32_f32_f32_len[reduc], arr_dmmv_id_f32_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {wg_size_subgroup, 1}, 1, false, use_subgroups, force_subgroup_size);
  3140. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", arr_dmmv_id_f16_f32_f32_len[reduc], arr_dmmv_id_f16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size);
  3141. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", arr_dmmv_id_bf16_f32_f32_len[reduc], arr_dmmv_id_bf16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size);
  3142. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", arr_dmmv_id_q4_0_f32_f32_len[reduc], arr_dmmv_id_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3143. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", arr_dmmv_id_q4_1_f32_f32_len[reduc], arr_dmmv_id_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3144. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", arr_dmmv_id_q5_0_f32_f32_len[reduc], arr_dmmv_id_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3145. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", arr_dmmv_id_q5_1_f32_f32_len[reduc], arr_dmmv_id_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3146. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", arr_dmmv_id_q8_0_f32_f32_len[reduc], arr_dmmv_id_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3147. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", arr_dmmv_id_q2_k_f32_f32_len[reduc16], arr_dmmv_id_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3148. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", arr_dmmv_id_q3_k_f32_f32_len[reduc16], arr_dmmv_id_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3149. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", arr_dmmv_id_q4_k_f32_f32_len[reduc16], arr_dmmv_id_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3150. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", arr_dmmv_id_q5_k_f32_f32_len[reduc16], arr_dmmv_id_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3151. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", arr_dmmv_id_q6_k_f32_f32_len[reduc16], arr_dmmv_id_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3152. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", arr_dmmv_id_iq1_s_f32_f32_len[reduc16], arr_dmmv_id_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3153. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", arr_dmmv_id_iq1_m_f32_f32_len[reduc16], arr_dmmv_id_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3154. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", arr_dmmv_id_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3155. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", arr_dmmv_id_iq2_xs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3156. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", arr_dmmv_id_iq2_s_f32_f32_len[reduc16], arr_dmmv_id_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3157. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", arr_dmmv_id_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3158. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", arr_dmmv_id_iq3_s_f32_f32_len[reduc16], arr_dmmv_id_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3159. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", arr_dmmv_id_iq4_xs_f32_f32_len[reduc16], arr_dmmv_id_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3160. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", arr_dmmv_id_iq4_nl_f32_f32_len[reduc16], arr_dmmv_id_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3161. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", arr_dmmv_id_mxfp4_f32_f32_len[reduc16], arr_dmmv_id_mxfp4_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3162. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3163. if (device->integer_dot_product) {
  3164. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3165. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3166. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_q8_1_f32", arr_dmmv_id_q4_0_q8_1_f32_len[reduc], arr_dmmv_id_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3167. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_q8_1_f32", arr_dmmv_id_q4_1_q8_1_f32_len[reduc], arr_dmmv_id_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3168. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_q8_1_f32", arr_dmmv_id_q5_0_q8_1_f32_len[reduc], arr_dmmv_id_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3169. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_q8_1_f32", arr_dmmv_id_q5_1_q8_1_f32_len[reduc], arr_dmmv_id_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3170. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_q8_1_f32", arr_dmmv_id_q8_0_q8_1_f32_len[reduc], arr_dmmv_id_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3171. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_q8_1_f32", arr_dmmv_id_mxfp4_q8_1_f32_len[reduc], arr_dmmv_id_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3172. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_q8_1_f32", arr_dmmv_id_q2_k_q8_1_f32_len[reduc], arr_dmmv_id_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3173. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_q8_1_f32", arr_dmmv_id_q3_k_q8_1_f32_len[reduc], arr_dmmv_id_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3174. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_q8_1_f32", arr_dmmv_id_q4_k_q8_1_f32_len[reduc], arr_dmmv_id_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3175. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_q8_1_f32", arr_dmmv_id_q5_k_q8_1_f32_len[reduc], arr_dmmv_id_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3176. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_q8_1_f32", arr_dmmv_id_q6_k_q8_1_f32_len[reduc], arr_dmmv_id_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3177. }
  3178. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3179. }
  3180. #if !defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3181. GGML_UNUSED(rm_stdq_int);
  3182. GGML_UNUSED(rm_kq_int);
  3183. #endif
  3184. // dequant shaders
  3185. 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);
  3186. 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);
  3187. 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);
  3188. 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);
  3189. 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);
  3190. 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);
  3191. 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);
  3192. 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);
  3193. 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);
  3194. 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);
  3195. 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);
  3196. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_S], "dequant_iq1_s", dequant_iq1_s_len, dequant_iq1_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3197. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_M], "dequant_iq1_m", dequant_iq1_m_len, dequant_iq1_m_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3198. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XXS], "dequant_iq2_xxs", dequant_iq2_xxs_len, dequant_iq2_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3199. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XS], "dequant_iq2_xs", dequant_iq2_xs_len, dequant_iq2_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3200. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_S], "dequant_iq2_s", dequant_iq2_s_len, dequant_iq2_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3201. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_XXS], "dequant_iq3_xxs", dequant_iq3_xxs_len, dequant_iq3_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3202. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_S], "dequant_iq3_s", dequant_iq3_s_len, dequant_iq3_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3203. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_XS], "dequant_iq4_xs", dequant_iq4_xs_len, dequant_iq4_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3204. 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);
  3205. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_MXFP4], "dequant_mxfp4", dequant_mxfp4_len, dequant_mxfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3206. // get_rows
  3207. 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);
  3208. 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);
  3209. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_BF16], "get_rows_bf16", get_rows_bf16_len, get_rows_bf16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3210. 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);
  3211. 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);
  3212. 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);
  3213. 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);
  3214. 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);
  3215. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q2_K], "get_rows_q2_k", get_rows_q2_k_len, get_rows_q2_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3216. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q3_K], "get_rows_q3_k", get_rows_q3_k_len, get_rows_q3_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3217. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_K], "get_rows_q4_k", get_rows_q4_k_len, get_rows_q4_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3218. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_K], "get_rows_q5_k", get_rows_q5_k_len, get_rows_q5_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3219. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q6_K], "get_rows_q6_k", get_rows_q6_k_len, get_rows_q6_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3220. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_S], "get_rows_iq1_s", get_rows_iq1_s_len, get_rows_iq1_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3221. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_M], "get_rows_iq1_m", get_rows_iq1_m_len, get_rows_iq1_m_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3222. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs", get_rows_iq2_xxs_len, get_rows_iq2_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3223. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs", get_rows_iq2_xs_len, get_rows_iq2_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3224. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_S], "get_rows_iq2_s", get_rows_iq2_s_len, get_rows_iq2_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3225. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs", get_rows_iq3_xxs_len, get_rows_iq3_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3226. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_S], "get_rows_iq3_s", get_rows_iq3_s_len, get_rows_iq3_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3227. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs", get_rows_iq4_xs_len, get_rows_iq4_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3228. 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);
  3229. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_MXFP4], "get_rows_mxfp4", get_rows_mxfp4_len, get_rows_mxfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3230. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_I32], "get_rows_i32", get_rows_i32_len, get_rows_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3231. 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);
  3232. 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);
  3233. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_BF16], "get_rows_bf16_f32", get_rows_bf16_f32_len, get_rows_bf16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3234. 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);
  3235. 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);
  3236. 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);
  3237. 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);
  3238. 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);
  3239. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q2_K], "get_rows_q2_k_f32", get_rows_q2_k_f32_len, get_rows_q2_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3240. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q3_K], "get_rows_q3_k_f32", get_rows_q3_k_f32_len, get_rows_q3_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3241. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_K], "get_rows_q4_k_f32", get_rows_q4_k_f32_len, get_rows_q4_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3242. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_K], "get_rows_q5_k_f32", get_rows_q5_k_f32_len, get_rows_q5_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3243. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q6_K], "get_rows_q6_k_f32", get_rows_q6_k_f32_len, get_rows_q6_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3244. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_S], "get_rows_iq1_s_f32", get_rows_iq1_s_f32_len, get_rows_iq1_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3245. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_M], "get_rows_iq1_m_f32", get_rows_iq1_m_f32_len, get_rows_iq1_m_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3246. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs_f32", get_rows_iq2_xxs_f32_len, get_rows_iq2_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3247. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs_f32", get_rows_iq2_xs_f32_len, get_rows_iq2_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3248. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_S], "get_rows_iq2_s_f32", get_rows_iq2_s_f32_len, get_rows_iq2_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3249. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs_f32", get_rows_iq3_xxs_f32_len, get_rows_iq3_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3250. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_S], "get_rows_iq3_s_f32", get_rows_iq3_s_f32_len, get_rows_iq3_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3251. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs_f32", get_rows_iq4_xs_f32_len, get_rows_iq4_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3252. 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);
  3253. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_MXFP4], "get_rows_mxfp4_f32", get_rows_mxfp4_f32_len, get_rows_mxfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3254. 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);
  3255. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_split_k_reduce, "fa_split_k_reduce", fa_split_k_reduce_len, fa_split_k_reduce_data, "main", 3, 5 * sizeof(uint32_t), {1, device->subgroup_size, 1}, {device->subgroup_size}, 1, true);
  3256. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3257. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_subgroup_len, quantize_q8_1_x4_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3258. } else {
  3259. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_len, quantize_q8_1_x4_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3260. }
  3261. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3262. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3263. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  3264. } else {
  3265. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  3266. }
  3267. }
  3268. 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", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_nc_push_constants), {1, 1, 1}, {}, 1);
  3269. 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);
  3270. 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);
  3271. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  3272. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_f32, "rms_norm_mul_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3273. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_partials_f32, "rms_norm_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  3274. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_partials_f32, "rms_norm_mul_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3275. if (device->float_controls_rte_fp16 &&
  3276. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3277. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_rope_f32_f32, "rms_norm_mul_rope_f32_f32", rms_norm_mul_rope_f32_f32_len, rms_norm_mul_rope_f32_f32_data, "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3278. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_rope_f32_f16, "rms_norm_mul_rope_f32_f16", rms_norm_mul_rope_f32_f16_rte_len, rms_norm_mul_rope_f32_f16_rte_data, "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3279. }
  3280. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_back_f32, "rms_norm_back_f32", rms_norm_back_f32_len, rms_norm_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  3281. ggml_vk_create_pipeline(device, device->pipeline_l2_norm_f32, "l2_norm_f32", l2_norm_f32_len, l2_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  3282. 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);
  3283. 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);
  3284. 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);
  3285. ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f32, "cpy_f16_f32", cpy_f16_f32_len, cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3286. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3287. ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3288. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3289. 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);
  3290. 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);
  3291. 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);
  3292. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f32, "contig_cpy_f16_f32", contig_cpy_f16_f32_len, contig_cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3293. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3294. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3295. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3296. ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_32, "cpy_transpose_32", cpy_transpose_32_len, cpy_transpose_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1);
  3297. ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_16, "cpy_transpose_16", cpy_transpose_16_len, cpy_transpose_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1);
  3298. if (device->float_controls_rte_fp16) {
  3299. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_rte_len, cpy_f32_q4_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3300. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_rte_len, cpy_f32_q4_1_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3301. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_rte_len, cpy_f32_q5_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3302. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_rte_len, cpy_f32_q5_1_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3303. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_rte_len, cpy_f32_q8_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3304. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_rte_len, cpy_f32_iq4_nl_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3305. } else {
  3306. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_len, cpy_f32_q4_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3307. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_len, cpy_f32_q4_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3308. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_len, cpy_f32_q5_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3309. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_len, cpy_f32_q5_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3310. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_len, cpy_f32_q8_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3311. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_len, cpy_f32_iq4_nl_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  3312. }
  3313. #define SET_ROWS(itype, rte) \
  3314. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F32], "set_rows_f32" #itype, set_rows_f32 ## itype ## rte ## _len, set_rows_f32 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3315. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F16], "set_rows_f16" #itype, set_rows_f16 ## itype ## rte ## _len, set_rows_f16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3316. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_BF16], "set_rows_bf16" #itype, set_rows_bf16 ## itype ## rte ## _len, set_rows_bf16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3317. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_0], "set_rows_q4_0" #itype, set_rows_q4_0 ## itype ## rte ## _len, set_rows_q4_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3318. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_1], "set_rows_q4_1" #itype, set_rows_q4_1 ## itype ## rte ## _len, set_rows_q4_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3319. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_0], "set_rows_q5_0" #itype, set_rows_q5_0 ## itype ## rte ## _len, set_rows_q5_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3320. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_1], "set_rows_q5_1" #itype, set_rows_q5_1 ## itype ## rte ## _len, set_rows_q5_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3321. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q8_0], "set_rows_q8_0" #itype, set_rows_q8_0 ## itype ## rte ## _len, set_rows_q8_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3322. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_IQ4_NL], "set_rows_iq4_nl" #itype, set_rows_iq4_nl ## itype ## rte ## _len, set_rows_iq4_nl ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  3323. if (device->float_controls_rte_fp16) {
  3324. SET_ROWS(_i32, _rte)
  3325. SET_ROWS(_i64, _rte)
  3326. } else {
  3327. SET_ROWS(_i32, )
  3328. SET_ROWS(_i64, )
  3329. }
  3330. #undef SET_ROWS
  3331. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q4_0], "cpy_q4_0_f32", cpy_q4_0_f32_len, cpy_q4_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_0), 1, 1}, {}, 1);
  3332. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q4_1], "cpy_q4_1_f32", cpy_q4_1_f32_len, cpy_q4_1_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_1), 1, 1}, {}, 1);
  3333. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q5_0], "cpy_q5_0_f32", cpy_q5_0_f32_len, cpy_q5_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_0), 1, 1}, {}, 1);
  3334. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q5_1], "cpy_q5_1_f32", cpy_q5_1_f32_len, cpy_q5_1_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_1), 1, 1}, {}, 1);
  3335. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_Q8_0], "cpy_q8_0_f32", cpy_q8_0_f32_len, cpy_q8_0_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_Q8_0), 1, 1}, {}, 1);
  3336. ggml_vk_create_pipeline(device, device->pipeline_cpy_quant_f32[GGML_TYPE_IQ4_NL], "cpy_iq4_nl_f32", cpy_iq4_nl_f32_len, cpy_iq4_nl_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {(uint32_t)ggml_blck_size(GGML_TYPE_IQ4_NL), 1, 1}, {}, 1);
  3337. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3338. std::string s;
  3339. s += std::string(src0_f16 ? "_f16" : "_f32");
  3340. s += std::string(src1_f16 ? "_f16" : "_f32");
  3341. s += std::string(dst_f16 ? "_f16" : "_f32");
  3342. return s;
  3343. };
  3344. bool rte = device->float_controls_rte_fp16;
  3345. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3346. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3347. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3348. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3349. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3350. CREATE_BINARY(add, , {0}, 4)
  3351. CREATE_BINARY(add, _norepeat, {1}, 4)
  3352. CREATE_BINARY(sub, , {0}, 3)
  3353. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3354. CREATE_BINARY(mul, , {0}, 3)
  3355. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3356. CREATE_BINARY(div, , {0}, 3)
  3357. CREATE_BINARY(div, _norepeat, {1}, 3)
  3358. CREATE_BINARY(add_rms, , {0}, 4)
  3359. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3360. #undef CREATE_BINARY
  3361. if (device->multi_add) {
  3362. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3363. ggml_vk_create_pipeline2(device, device->pipeline_multi_add[i], "multi_add_f32_" + std::to_string(i+1), multi_add_f32_len, multi_add_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  3364. ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms[i], "multi_add_rms_f32_" + std::to_string(i+1), multi_add_rms_f32_len, multi_add_rms_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  3365. }
  3366. }
  3367. ggml_vk_create_pipeline(device, device->pipeline_add_id_f32, "add_id_f32", add_id_f32_len, add_id_f32_data, "main", 4, sizeof(vk_op_add_id_push_constants), {1, 1, 1}, {}, 1);
  3368. 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);
  3369. 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);
  3370. 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);
  3371. 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);
  3372. ggml_vk_create_pipeline(device, device->pipeline_upscale_nearest_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_NEAREST}, 1);
  3373. ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR}, 1);
  3374. ggml_vk_create_pipeline(device, device->pipeline_upscale_bicubic_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BICUBIC}, 1);
  3375. 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);
  3376. 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);
  3377. ggml_vk_create_pipeline(device, device->pipeline_sqrt_f32, "sqrt_f32", sqrt_f32_len, sqrt_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3378. 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);
  3379. 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);
  3380. if (device->float_controls_rte_fp16) {
  3381. ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32_rte", log_f32_rte_len, log_f32_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3382. ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16_rte", log_f16_rte_len, log_f16_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3383. } else {
  3384. ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32", log_f32_len, log_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3385. ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16", log_f16_len, log_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3386. }
  3387. ggml_vk_create_pipeline(device, device->pipeline_tri[0], "tri_f32", tri_f32_len, tri_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3388. ggml_vk_create_pipeline(device, device->pipeline_tri[1], "tri_f16", tri_f16_len, tri_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3389. ggml_vk_create_pipeline(device, device->pipeline_diag[0], "diag_f32", diag_f32_len, diag_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3390. ggml_vk_create_pipeline(device, device->pipeline_diag[1], "diag_f16", diag_f16_len, diag_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3391. 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);
  3392. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_pad_push_constants), {512, 1, 1}, {}, 1);
  3393. ggml_vk_create_pipeline(device, device->pipeline_roll_f32, "roll_f32", roll_f32_len, roll_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3394. 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);
  3395. ggml_vk_create_pipeline(device, device->pipeline_repeat_back_f32, "repeat_back_f32", repeat_back_f32_len, repeat_back_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3396. #define CREATE_UNARY(name) \
  3397. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3398. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3399. CREATE_UNARY(gelu)
  3400. CREATE_UNARY(gelu_erf)
  3401. CREATE_UNARY(gelu_quick)
  3402. CREATE_UNARY(silu)
  3403. CREATE_UNARY(relu)
  3404. CREATE_UNARY(neg)
  3405. CREATE_UNARY(tanh)
  3406. CREATE_UNARY(sigmoid)
  3407. CREATE_UNARY(hardsigmoid)
  3408. CREATE_UNARY(hardswish)
  3409. CREATE_UNARY(abs)
  3410. CREATE_UNARY(softplus)
  3411. CREATE_UNARY(step)
  3412. CREATE_UNARY(round)
  3413. CREATE_UNARY(ceil)
  3414. CREATE_UNARY(floor)
  3415. CREATE_UNARY(trunc)
  3416. #undef CREATE_UNARY
  3417. #define CREATE_UNARY_RTE(name) \
  3418. if (device->float_controls_rte_fp16) { \
  3419. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3420. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3421. } else { \
  3422. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3423. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3424. }
  3425. CREATE_UNARY_RTE(exp)
  3426. #undef CREATE_UNARY_RTE
  3427. ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f16, "add1_f16_f16", add1_f16_f16_len, add1_f16_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3428. ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f32, "add1_f16_f32", add1_f16_f32_len, add1_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3429. ggml_vk_create_pipeline(device, device->pipeline_add1_f32_f32, "add1_f32_f32", add1_f32_f32_len, add1_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3430. ggml_vk_create_pipeline(device, device->pipeline_arange_f32, "arange_f32", arange_f32_len, arange_f32_data, "main", 1, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3431. ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3432. #define CREATE_GLU(name) \
  3433. if (device->float_controls_rte_fp16) { \
  3434. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3435. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3436. } else { \
  3437. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3438. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  3439. }
  3440. CREATE_GLU(geglu)
  3441. CREATE_GLU(reglu)
  3442. CREATE_GLU(swiglu)
  3443. CREATE_GLU(swiglu_oai)
  3444. CREATE_GLU(geglu_erf)
  3445. CREATE_GLU(geglu_quick)
  3446. #undef CREATE_GLU
  3447. 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);
  3448. ggml_vk_create_pipeline(device, device->pipeline_silu_back_f32, "silu_back_f32", silu_back_f32_len, silu_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3449. ggml_vk_create_pipeline(device, device->pipeline_diag_mask_inf_f32, "diag_mask_inf_f32", diag_mask_inf_f32_len, diag_mask_inf_f32_data, "main", 2, sizeof(vk_op_diag_mask_push_constants), {1, 512, 1}, {}, 1, true);
  3450. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3451. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  3452. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3453. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  3454. ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true);
  3455. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32, "soft_max_large1_f32", soft_max_large1_f32_len, soft_max_large1_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3456. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large2_f32, "soft_max_large2_f32", soft_max_large2_f32_len, soft_max_large2_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3457. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large3_f32, "soft_max_large3_f32", soft_max_large3_f32_len, soft_max_large3_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3458. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32_f16, "soft_max_large1_f32_f16", soft_max_large1_f32_f16_len, soft_max_large1_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3459. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large2_f32_f16, "soft_max_large2_f32_f16", soft_max_large2_f32_f16_len, soft_max_large2_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3460. ggml_vk_create_pipeline(device, device->pipeline_soft_max_large3_f32_f16, "soft_max_large3_f32_f16", soft_max_large3_f32_f16_len, soft_max_large3_f32_f16_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true);
  3461. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3462. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3463. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32, "rope_multi_f32", rope_multi_f32_len, rope_multi_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3464. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f32, "rope_vision_f32", rope_vision_f32_len, rope_vision_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3465. if (device->float_controls_rte_fp16) {
  3466. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_rte_len, rope_norm_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3467. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_rte_len, rope_neox_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3468. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_rte_len, rope_multi_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3469. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_rte_len, rope_vision_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3470. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_rte_len, rope_norm_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3471. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_rte_len, rope_neox_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3472. } else {
  3473. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3474. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3475. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_len, rope_multi_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3476. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_len, rope_vision_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3477. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_len, rope_norm_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3478. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_len, rope_neox_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3479. }
  3480. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3481. uint32_t BLOCK_SIZE = 1u << std::min(i, device->max_workgroup_size_log2);
  3482. if (i <= device->max_workgroup_size_log2 &&
  3483. 2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3484. const uint32_t NCOLS_PADDED_LOG2 = i;
  3485. ggml_vk_create_pipeline2(device, device->pipeline_argsort_f32[i], "argsort_f32_"+std::to_string(i), argsort_f32_len, argsort_f32_data, "main", 3, sizeof(vk_op_argsort_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, NCOLS_PADDED_LOG2}, 1, true);
  3486. }
  3487. const uint32_t WG_UNROLL_FACTOR = BLOCK_SIZE > 1 ? 2 : 1;
  3488. BLOCK_SIZE /= WG_UNROLL_FACTOR;
  3489. ggml_vk_create_pipeline2(device, device->pipeline_argsort_large_f32[i], "argsort_large_f32_"+std::to_string(i), argsort_large_f32_len, argsort_large_f32_data, "main", 3, sizeof(vk_op_argsort_push_constants), {BLOCK_SIZE * WG_UNROLL_FACTOR, 1, 1}, {BLOCK_SIZE, WG_UNROLL_FACTOR}, 1, true);
  3490. }
  3491. for (uint32_t i = 0; i < num_topk_pipelines; ++i) {
  3492. const uint32_t BLOCK_SIZE = 1u << i;
  3493. const uint32_t NCOLS_PADDED_LOG2 = i;
  3494. if (i <= device->max_workgroup_size_log2) {
  3495. uint32_t nary_shmem = 2 * sizeof(int) * BLOCK_SIZE +
  3496. sizeof(int) * device->subgroup_size +
  3497. 2 * sizeof(int) +
  3498. 2 * (BLOCK_SIZE / device->subgroup_size) * sizeof(int);
  3499. if (device->subgroup_arithmetic && device->subgroup_require_full_support && device->subgroup_shuffle && device->subgroup_ballot &&
  3500. nary_shmem <= device->properties.limits.maxComputeSharedMemorySize) {
  3501. ggml_vk_create_pipeline2(device, device->pipeline_topk_f32[i], "topk_f32_"+std::to_string(i), topk_nary_search_f32_len, topk_nary_search_f32_data, "main", 2, sizeof(vk_op_topk_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, device->subgroup_size, device->subgroup_size_log2}, 1, true, true, device->subgroup_size);
  3502. } else if (2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3503. ggml_vk_create_pipeline2(device, device->pipeline_topk_f32[i], "topk_f32_"+std::to_string(i), topk_argsort_f32_len, topk_argsort_f32_data, "main", 2, sizeof(vk_op_topk_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, NCOLS_PADDED_LOG2}, 1, true);
  3504. }
  3505. }
  3506. }
  3507. ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3508. ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3509. ggml_vk_create_pipeline(device, device->pipeline_cumsum_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 128, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3510. ggml_vk_create_pipeline(device, device->pipeline_count_equal_i32, "count_equal_i32", count_equal_i32_len, count_equal_i32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, { device->subgroup_size }, 1);
  3511. for (auto &s : device->pipeline_solve_tri_f32) {
  3512. const vk_solve_tri_pipeline_state &state = s.first;
  3513. // Max number of rows to load at a time, limited by shared memory
  3514. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((state.N + state.K) * sizeof(float));
  3515. // Need at least K invocations, and prefer a minimum of 128 to spread out loading shared memory
  3516. const uint32_t block_size = std::max(128u, 1u << (uint32_t)ceilf(log2f(float(state.K))));
  3517. ggml_vk_create_pipeline(
  3518. device, s.second, "solve_tri_f32",
  3519. solve_tri_f32_len, solve_tri_f32_data, "main", 3,
  3520. sizeof(vk_op_binary_push_constants), {1, 1, 1}, { 0, state.N, state.K, batch_N, block_size }, 1, true);
  3521. }
  3522. #define IM2COL(bda) \
  3523. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32 ## bda ## _len, im2col_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3524. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32, "im2col_3d_f32", im2col_3d_f32 ## bda ## _len, im2col_3d_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3525. if (device->float_controls_rte_fp16) { \
  3526. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_rte ## bda ## _len, im2col_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3527. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16_rte ## bda ## _len, im2col_3d_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3528. } else { \
  3529. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16 ## bda ## _len, im2col_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3530. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16 ## bda ## _len, im2col_3d_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3531. }
  3532. if (device->shader_int64 && device->buffer_device_address) {
  3533. IM2COL(_bda)
  3534. } else {
  3535. IM2COL()
  3536. }
  3537. 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);
  3538. ggml_vk_create_pipeline(device, device->pipeline_conv_transpose_1d_f32, "conv_transpose_1d_f32", conv_transpose_1d_f32_len, conv_transpose_1d_f32_data, "main", 3, sizeof(vk_op_conv_transpose_1d_push_constants), {1, 1, 1}, {}, 1);
  3539. 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);
  3540. ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv6_f32, "rwkv_wkv6_f32", rwkv_wkv6_f32_len, rwkv_wkv6_f32_data, "main", 7, sizeof(vk_op_rwkv_wkv6_push_constants), {1, 1, 1}, {device->subgroup_size}, 1);
  3541. ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv7_f32, "rwkv_wkv7_f32", rwkv_wkv7_f32_len, rwkv_wkv7_f32_data, "main", 8, sizeof(vk_op_rwkv_wkv7_push_constants), {1, 1, 1}, {device->subgroup_size}, 1);
  3542. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3543. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
  3544. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
  3545. } else {
  3546. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
  3547. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
  3548. }
  3549. ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 3, sizeof(vk_op_ssm_conv_push_constants), {32, 1, 1}, {32}, 1);
  3550. ggml_vk_create_pipeline(device, device->pipeline_opt_step_adamw_f32, "opt_step_adamw_f32", opt_step_adamw_f32_len, opt_step_adamw_f32_data, "main", 5, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3551. ggml_vk_create_pipeline(device, device->pipeline_opt_step_sgd_f32, "opt_step_sgd_f32", opt_step_sgd_f32_len, opt_step_sgd_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3552. // conv2d, conv_transpose_2d
  3553. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3554. uint32_t conv2d_WG_SIZE = 256;
  3555. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3556. uint32_t conv2d_TS_K = (s == CONV_SHAPE_64x32) ? 4 : 8;
  3557. uint32_t conv2d_SHMEM_PAD = 4;
  3558. vk_conv_block_size conv2d_BS = vk_conv_block_sizes[s];
  3559. bool conv2d_UNROLL = true;
  3560. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3561. if (device->coopmat2) {
  3562. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3563. }
  3564. #endif
  3565. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3566. conv2d_SHMEM_PAD = 0;
  3567. conv2d_UNROLL = false;
  3568. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3569. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3570. if (s == CONV_SHAPE_128x128 && device->architecture != vk_device_architecture::AMD_GCN) {
  3571. conv2d_UNROLL = false;
  3572. }
  3573. }
  3574. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3575. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3576. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3577. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3578. device->architecture == vk_device_architecture::AMD_GCN;
  3579. if (device->subgroup_shuffle &&
  3580. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3581. allow_collectives_nv &&
  3582. allow_collectives_amd) {
  3583. use_collectives = 1;
  3584. conv2d_BS.CRS = std::min(
  3585. device->subgroup_size,
  3586. conv2d_BS.CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3587. }
  3588. uint32_t conv2d_shmem_req =
  3589. (conv2d_BS.K * (conv2d_BS.CRS + conv2d_SHMEM_PAD) + conv2d_BS.CRS * (conv2d_BS.NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3590. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3591. conv2d_BS.CRS = 8;
  3592. if (use_collectives) {
  3593. conv2d_BS.CRS = std::min(device->subgroup_size, conv2d_BS.CRS);
  3594. }
  3595. }
  3596. std::array<uint32_t, 3> wg_denoms = { conv2d_BS.K, 1, 1 };
  3597. std::vector<uint32_t> spec_constants = { conv2d_WG_SIZE, conv2d_BS.K, conv2d_BS.CRS, conv2d_BS.NPQ, conv2d_TS_K, use_collectives, conv2d_SHMEM_PAD };
  3598. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3599. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3600. const vk_conv2d_pipeline_state &state = c.first; \
  3601. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3602. spec_constants_cpy.push_back(state.s0); \
  3603. spec_constants_cpy.push_back(state.s1); \
  3604. spec_constants_cpy.push_back(state.p0); \
  3605. spec_constants_cpy.push_back(state.p1); \
  3606. spec_constants_cpy.push_back(state.d0); \
  3607. spec_constants_cpy.push_back(state.d1); \
  3608. spec_constants_cpy.push_back(state.KW); \
  3609. spec_constants_cpy.push_back(state.KH); \
  3610. ggml_vk_create_pipeline( \
  3611. device, c.second, #name #type_suffix, \
  3612. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3613. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3614. }
  3615. #define CREATE_CONVS(spv_suffix) \
  3616. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3617. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3618. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3619. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix)
  3620. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3621. if (device->coopmat2) {
  3622. CREATE_CONVS(_cm2)
  3623. } else
  3624. #endif
  3625. if (conv2d_UNROLL) {
  3626. CREATE_CONVS(_unroll)
  3627. } else {
  3628. CREATE_CONVS( )
  3629. }
  3630. #undef CREATE_CONV
  3631. #undef CREATE_CONVS
  3632. }
  3633. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f32, "conv2d_dw_whcn_f32", conv2d_dw_whcn_f32_len, conv2d_dw_whcn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3634. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f32, "conv2d_dw_cwhn_f32", conv2d_dw_cwhn_f32_len, conv2d_dw_cwhn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3635. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f16_f32, "conv2d_dw_whcn_f16_f32", conv2d_dw_whcn_f16_f32_len, conv2d_dw_whcn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3636. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f16_f32, "conv2d_dw_cwhn_f16_f32", conv2d_dw_cwhn_f16_f32_len, conv2d_dw_cwhn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3637. for (uint32_t use_push = 0; use_push < 2; ++use_push) {
  3638. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3639. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX][use_push], "topk_moe_f32_early_softmax_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 0, use_push}, 1, true, true, device->subgroup_size);
  3640. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX_NORM][use_push], "topk_moe_f32_early_softmax_norm"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 1, 0, use_push}, 1, true, true, device->subgroup_size);
  3641. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_LATE_SOFTMAX][use_push], "topk_moe_f32_late_softmax"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 1, use_push}, 1, true, true, device->subgroup_size);
  3642. }
  3643. }
  3644. for (auto &c : compiles) {
  3645. c.wait();
  3646. }
  3647. }
  3648. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3649. static vk_device ggml_vk_get_device(size_t idx) {
  3650. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3651. if (vk_instance.devices[idx] == nullptr) {
  3652. VK_LOG_DEBUG("Initializing new vk_device");
  3653. vk_device device = std::make_shared<vk_device_struct>();
  3654. vk_instance.devices[idx] = device;
  3655. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3656. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3657. #endif
  3658. size_t dev_num = vk_instance.device_indices[idx];
  3659. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3660. if (dev_num >= physical_devices.size()) {
  3661. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3662. throw std::runtime_error("Device not found");
  3663. }
  3664. device->physical_device = physical_devices[dev_num];
  3665. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3666. device->architecture = get_device_architecture(device->physical_device);
  3667. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3668. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3669. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3670. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3671. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3672. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3673. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3674. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3675. bool fp16_storage = false;
  3676. bool fp16_compute = false;
  3677. bool maintenance4_support = false;
  3678. bool sm_builtins = false;
  3679. bool amd_shader_core_properties2 = false;
  3680. bool pipeline_robustness = false;
  3681. bool coopmat2_support = false;
  3682. bool pipeline_executable_properties_support = false;
  3683. device->coopmat_support = false;
  3684. device->integer_dot_product = false;
  3685. bool bfloat16_support = false;
  3686. for (const auto& properties : ext_props) {
  3687. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3688. maintenance4_support = true;
  3689. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3690. fp16_storage = true;
  3691. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3692. fp16_compute = true;
  3693. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3694. sm_builtins = true;
  3695. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3696. amd_shader_core_properties2 = true;
  3697. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3698. pipeline_robustness = true;
  3699. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3700. device->subgroup_size_control = true;
  3701. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3702. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3703. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3704. device->coopmat_support = true;
  3705. device->coopmat_m = 0;
  3706. device->coopmat_n = 0;
  3707. device->coopmat_k = 0;
  3708. #endif
  3709. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3710. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3711. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3712. coopmat2_support = true;
  3713. #endif
  3714. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3715. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3716. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3717. device->integer_dot_product = true;
  3718. #endif
  3719. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3720. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3721. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3722. bfloat16_support = true;
  3723. #endif
  3724. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3725. pipeline_executable_properties_support = true;
  3726. } else if (strcmp("VK_EXT_memory_priority", properties.extensionName) == 0 &&
  3727. getenv("GGML_VK_ENABLE_MEMORY_PRIORITY")) {
  3728. device->memory_priority = true;
  3729. }
  3730. }
  3731. vk::PhysicalDeviceProperties2 props2;
  3732. vk::PhysicalDeviceMaintenance3Properties props3;
  3733. vk::PhysicalDeviceMaintenance4Properties props4;
  3734. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3735. vk::PhysicalDeviceDriverProperties driver_props;
  3736. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3737. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3738. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3739. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3740. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3741. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3742. props2.pNext = &props3;
  3743. props3.pNext = &subgroup_props;
  3744. subgroup_props.pNext = &driver_props;
  3745. driver_props.pNext = &vk11_props;
  3746. vk11_props.pNext = &vk12_props;
  3747. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3748. if (maintenance4_support) {
  3749. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3750. last_struct = (VkBaseOutStructure *)&props4;
  3751. }
  3752. if (sm_builtins) {
  3753. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3754. last_struct = (VkBaseOutStructure *)&sm_props;
  3755. }
  3756. if (amd_shader_core_properties2) {
  3757. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3758. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3759. }
  3760. if (device->subgroup_size_control) {
  3761. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3762. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3763. }
  3764. #if defined(VK_NV_cooperative_matrix2)
  3765. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3766. if (coopmat2_support) {
  3767. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3768. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3769. }
  3770. #endif
  3771. if (device->integer_dot_product) {
  3772. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3773. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3774. }
  3775. device->physical_device.getProperties2(&props2);
  3776. device->properties = props2.properties;
  3777. device->vendor_id = device->properties.vendorID;
  3778. device->driver_id = driver_props.driverID;
  3779. // Implementing the async backend interfaces seems broken on older Intel HW,
  3780. // see https://github.com/ggml-org/llama.cpp/issues/17302.
  3781. device->support_async = (device->vendor_id != VK_VENDOR_ID_INTEL ||
  3782. std::string(device->properties.deviceName.data()).find("(DG1)") == std::string::npos) &&
  3783. getenv("GGML_VK_DISABLE_ASYNC") == nullptr;
  3784. if (!device->support_async) {
  3785. GGML_LOG_DEBUG("ggml_vulkan: WARNING: Async execution disabled on certain Intel devices.\n");
  3786. }
  3787. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3788. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3789. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3790. } else if (maintenance4_support) {
  3791. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3792. } else {
  3793. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3794. }
  3795. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3796. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3797. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3798. } else if (maintenance4_support) {
  3799. device->max_buffer_size = props4.maxBufferSize;
  3800. } else {
  3801. device->max_buffer_size = device->max_memory_allocation_size;
  3802. }
  3803. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3804. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3805. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3806. } else {
  3807. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3808. device->suballocation_block_size = 1024*1024*1024;
  3809. }
  3810. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3811. device->subgroup_size = subgroup_props.subgroupSize;
  3812. device->subgroup_size_log2 = uint32_t(log2f(float(device->subgroup_size)));
  3813. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3814. if (sm_builtins) {
  3815. device->shader_core_count = sm_props.shaderSMCount;
  3816. } else if (amd_shader_core_properties2) {
  3817. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3818. } else {
  3819. device->shader_core_count = 0;
  3820. }
  3821. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3822. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3823. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3824. #ifdef __APPLE__
  3825. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3826. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3827. device->subgroup_arithmetic = false;
  3828. }
  3829. #endif
  3830. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3831. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3832. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3833. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3834. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3835. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3836. device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3837. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote);
  3838. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3839. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3840. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3841. device->coopmat_support = false;
  3842. }
  3843. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3844. device->max_workgroup_size_log2 = uint32_t(log2f(float(device->properties.limits.maxComputeWorkGroupInvocations)));
  3845. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3846. // Try to find a non-graphics compute queue and transfer-focused queues
  3847. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3848. 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);
  3849. const float priorities[] = { 1.0f, 1.0f };
  3850. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3851. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3852. if (compute_queue_family_index != transfer_queue_family_index) {
  3853. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3854. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3855. } else if(!device->single_queue) {
  3856. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3857. } else {
  3858. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3859. }
  3860. vk::DeviceCreateInfo device_create_info;
  3861. std::vector<const char *> device_extensions;
  3862. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3863. VkPhysicalDeviceFeatures2 device_features2;
  3864. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3865. device_features2.pNext = nullptr;
  3866. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3867. VkPhysicalDeviceVulkan11Features vk11_features;
  3868. vk11_features.pNext = nullptr;
  3869. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3870. device_features2.pNext = &vk11_features;
  3871. VkPhysicalDeviceVulkan12Features vk12_features;
  3872. vk12_features.pNext = nullptr;
  3873. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3874. vk11_features.pNext = &vk12_features;
  3875. last_struct = (VkBaseOutStructure *)&vk12_features;
  3876. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3877. pl_robustness_features.pNext = nullptr;
  3878. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3879. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3880. if (pipeline_robustness) {
  3881. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3882. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3883. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3884. }
  3885. VkPhysicalDeviceMemoryPriorityFeaturesEXT memory_priority_features;
  3886. memory_priority_features.pNext = nullptr;
  3887. memory_priority_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT;
  3888. memory_priority_features.memoryPriority = VK_FALSE;
  3889. if (device->memory_priority) {
  3890. last_struct->pNext = (VkBaseOutStructure *)&memory_priority_features;
  3891. last_struct = (VkBaseOutStructure *)&memory_priority_features;
  3892. device_extensions.push_back("VK_EXT_memory_priority");
  3893. }
  3894. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3895. subgroup_size_control_features.pNext = nullptr;
  3896. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3897. subgroup_size_control_features.computeFullSubgroups = false;
  3898. subgroup_size_control_features.subgroupSizeControl = false;
  3899. if (device->subgroup_size_control) {
  3900. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3901. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3902. }
  3903. #if defined(VK_KHR_cooperative_matrix)
  3904. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3905. coopmat_features.pNext = nullptr;
  3906. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3907. coopmat_features.cooperativeMatrix = VK_FALSE;
  3908. if (device->coopmat_support) {
  3909. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3910. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3911. }
  3912. #endif
  3913. #if defined(VK_NV_cooperative_matrix2)
  3914. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3915. coopmat2_features.pNext = nullptr;
  3916. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3917. if (coopmat2_support) {
  3918. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3919. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3920. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3921. }
  3922. #endif
  3923. #if defined(VK_KHR_shader_bfloat16)
  3924. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3925. bfloat16_features.pNext = nullptr;
  3926. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3927. if (bfloat16_support) {
  3928. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3929. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3930. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3931. }
  3932. #endif
  3933. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3934. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3935. if (maintenance4_support) {
  3936. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3937. last_struct = (VkBaseOutStructure *)&maint4_features;
  3938. device_extensions.push_back("VK_KHR_maintenance4");
  3939. }
  3940. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3941. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3942. if (device->integer_dot_product) {
  3943. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3944. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3945. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3946. }
  3947. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3948. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3949. if (pipeline_executable_properties_support) {
  3950. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3951. last_struct = (VkBaseOutStructure *)&pep_features;
  3952. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3953. }
  3954. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3955. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3956. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3957. #if defined(VK_KHR_shader_bfloat16)
  3958. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3959. #else
  3960. device->bf16 = false;
  3961. #endif
  3962. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3963. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3964. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3965. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3966. device->shader_int64 = device_features2.features.shaderInt64;
  3967. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3968. device->vulkan_memory_model = vk12_features.vulkanMemoryModel;
  3969. if (device->subgroup_size_control) {
  3970. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3971. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3972. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3973. }
  3974. device->subgroup_size_control = device->subgroup_size_control &&
  3975. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3976. subgroup_size_control_features.subgroupSizeControl;
  3977. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3978. #if defined(VK_KHR_cooperative_matrix)
  3979. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3980. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3981. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3982. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3983. device->subgroup_max_size >= 32;
  3984. #endif
  3985. if (coopmat2_support) {
  3986. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3987. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3988. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3989. coopmat2_features.cooperativeMatrixReductions &&
  3990. coopmat2_features.cooperativeMatrixConversions &&
  3991. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3992. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3993. coopmat2_features.cooperativeMatrixBlockLoads &&
  3994. vk12_features.bufferDeviceAddress) {
  3995. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3996. uint32_t count = 0;
  3997. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3998. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3999. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  4000. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  4001. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  4002. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  4003. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  4004. flexible_dimensions.resize(count, empty_prop);
  4005. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  4006. bool found_fp16_128 = false,
  4007. found_fp16_256 = false,
  4008. found_fp32_128 = false,
  4009. found_fp32_256 = false;
  4010. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  4011. // with 32x16x16 and 256 with 32x32x16.
  4012. for (auto &prop : flexible_dimensions) {
  4013. if (prop.saturatingAccumulation == VK_FALSE &&
  4014. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  4015. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4016. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4017. if (prop.workgroupInvocations == 128 &&
  4018. prop.MGranularity <= 32 &&
  4019. prop.NGranularity <= 16 &&
  4020. prop.KGranularity <= 16) {
  4021. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4022. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4023. found_fp16_128 = true;
  4024. }
  4025. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4026. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4027. found_fp32_128 = true;
  4028. }
  4029. }
  4030. if (prop.workgroupInvocations == 256 &&
  4031. prop.MGranularity <= 32 &&
  4032. prop.NGranularity <= 32 &&
  4033. prop.KGranularity <= 16) {
  4034. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4035. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4036. found_fp16_256 = true;
  4037. }
  4038. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4039. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4040. found_fp32_256 = true;
  4041. }
  4042. }
  4043. }
  4044. }
  4045. if (found_fp16_128 && found_fp16_256 &&
  4046. found_fp32_128 && found_fp32_256 &&
  4047. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  4048. device->coopmat2 = true;
  4049. }
  4050. }
  4051. #endif
  4052. }
  4053. if (!vk11_features.storageBuffer16BitAccess) {
  4054. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  4055. throw std::runtime_error("Unsupported device");
  4056. }
  4057. device_extensions.push_back("VK_KHR_16bit_storage");
  4058. #ifdef GGML_VULKAN_VALIDATE
  4059. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  4060. #endif
  4061. if (device->fp16) {
  4062. device_extensions.push_back("VK_KHR_shader_float16_int8");
  4063. }
  4064. #if defined(VK_KHR_cooperative_matrix)
  4065. if (device->coopmat_support) {
  4066. // Query supported shapes
  4067. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  4068. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  4069. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  4070. uint32_t cm_props_num;
  4071. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  4072. cm_props.resize(cm_props_num);
  4073. for (auto& prop : cm_props) {
  4074. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  4075. }
  4076. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  4077. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  4078. for (auto& prop : cm_props) {
  4079. 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));
  4080. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  4081. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  4082. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4083. ) {
  4084. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  4085. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  4086. // coopmat sizes not set yet
  4087. if (device->coopmat_m == 0) {
  4088. device->coopmat_acc_f32_support = true;
  4089. device->coopmat_m = prop.MSize;
  4090. device->coopmat_n = prop.NSize;
  4091. device->coopmat_k = prop.KSize;
  4092. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4093. // Only enable if shape is identical
  4094. device->coopmat_acc_f32_support = true;
  4095. }
  4096. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4097. device->coopmat_support_16x16x16_f32acc = true;
  4098. }
  4099. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  4100. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  4101. // coopmat sizes not set yet
  4102. if (device->coopmat_m == 0) {
  4103. device->coopmat_acc_f16_support = true;
  4104. device->coopmat_m = prop.MSize;
  4105. device->coopmat_n = prop.NSize;
  4106. device->coopmat_k = prop.KSize;
  4107. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4108. // Only enable if shape is identical
  4109. device->coopmat_acc_f16_support = true;
  4110. }
  4111. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4112. device->coopmat_support_16x16x16_f16acc = true;
  4113. }
  4114. }
  4115. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  4116. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  4117. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  4118. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  4119. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  4120. device->coopmat_int_m == 0
  4121. ) {
  4122. device->coopmat_int_support = true;
  4123. device->coopmat_int_m = prop.MSize;
  4124. device->coopmat_int_n = prop.NSize;
  4125. device->coopmat_int_k = prop.KSize;
  4126. }
  4127. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4128. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4129. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4130. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4131. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4132. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4133. ) {
  4134. // coopmat sizes not set yet
  4135. if (device->coopmat_m == 0) {
  4136. device->coopmat_bf16_support = true;
  4137. device->coopmat_m = prop.MSize;
  4138. device->coopmat_n = prop.NSize;
  4139. device->coopmat_k = prop.KSize;
  4140. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4141. // Only enable if shape is identical
  4142. device->coopmat_bf16_support = true;
  4143. }
  4144. }
  4145. #endif
  4146. }
  4147. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  4148. // No suitable matmul mode found
  4149. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  4150. device->coopmat_support = false;
  4151. }
  4152. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4153. device->coopmat_bf16_support = false;
  4154. }
  4155. }
  4156. if (device->coopmat_support) {
  4157. device_extensions.push_back("VK_KHR_cooperative_matrix");
  4158. }
  4159. #if defined(VK_KHR_shader_bfloat16)
  4160. if (device->coopmat_bf16_support) {
  4161. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4162. }
  4163. #endif
  4164. #endif
  4165. device->name = GGML_VK_NAME + std::to_string(idx);
  4166. device_create_info = {
  4167. vk::DeviceCreateFlags(),
  4168. device_queue_create_infos,
  4169. {},
  4170. device_extensions
  4171. };
  4172. device_create_info.setPNext(&device_features2);
  4173. device->device = device->physical_device.createDevice(device_create_info);
  4174. // Queues
  4175. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  4176. // Shaders
  4177. // Disable matmul tile sizes early if performance low or not supported
  4178. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  4179. switch (device->vendor_id) {
  4180. #ifndef GGML_VULKAN_RUN_TESTS
  4181. case VK_VENDOR_ID_AMD:
  4182. case VK_VENDOR_ID_INTEL:
  4183. device->mul_mat_l[i] = false;
  4184. device->mul_mat_m[i] = true;
  4185. device->mul_mat_s[i] = true;
  4186. device->mul_mat_id_l[i] = false;
  4187. device->mul_mat_id_m[i] = true;
  4188. device->mul_mat_id_s[i] = true;
  4189. break;
  4190. case VK_VENDOR_ID_APPLE:
  4191. device->mul_mat_l[i] = false;
  4192. device->mul_mat_m[i] = true;
  4193. device->mul_mat_s[i] = false;
  4194. device->mul_mat_id_l[i] = false;
  4195. device->mul_mat_id_m[i] = true;
  4196. device->mul_mat_id_s[i] = false;
  4197. break;
  4198. #endif
  4199. default:
  4200. device->mul_mat_l[i] = true;
  4201. device->mul_mat_m[i] = true;
  4202. device->mul_mat_s[i] = true;
  4203. device->mul_mat_id_l[i] = true;
  4204. device->mul_mat_id_m[i] = true;
  4205. device->mul_mat_id_s[i] = true;
  4206. break;
  4207. }
  4208. }
  4209. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  4210. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  4211. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  4212. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  4213. dsl_binding_flags.push_back({});
  4214. }
  4215. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  4216. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  4217. {},
  4218. dsl_binding);
  4219. descriptor_set_layout_create_info.setPNext(&dslbfci);
  4220. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  4221. ggml_vk_load_shaders(device);
  4222. if (!device->single_queue) {
  4223. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  4224. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  4225. } else {
  4226. // TODO: Use pointer or reference to avoid copy
  4227. device->transfer_queue.copyFrom(device->compute_queue);
  4228. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  4229. }
  4230. device->buffer_type = {
  4231. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4232. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  4233. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  4234. };
  4235. device->fence = device->device.createFence({});
  4236. device->idx = idx;
  4237. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  4238. device->add_rms_fusion = !device->disable_fusion &&
  4239. device->subgroup_arithmetic &&
  4240. device->vendor_id != VK_VENDOR_ID_INTEL;
  4241. device->partials_binding_alignment =
  4242. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  4243. device->mmvq_mode = 0;
  4244. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  4245. device->mmvq_mode = -1;
  4246. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  4247. device->mmvq_mode = 1;
  4248. }
  4249. return device;
  4250. }
  4251. return vk_instance.devices[idx];
  4252. }
  4253. static void ggml_vk_print_gpu_info(size_t idx) {
  4254. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4255. size_t dev_num = vk_instance.device_indices[idx];
  4256. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4257. GGML_ASSERT(vk_instance_initialized);
  4258. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4259. if (dev_num >= devices.size()) {
  4260. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4261. throw std::runtime_error("Device not found");
  4262. }
  4263. vk::PhysicalDevice physical_device = devices[dev_num];
  4264. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4265. bool fp16_storage = false;
  4266. bool fp16_compute = false;
  4267. bool coopmat_support = false;
  4268. bool coopmat2_support = false;
  4269. bool integer_dot_product = false;
  4270. bool bfloat16_support = false;
  4271. for (auto properties : ext_props) {
  4272. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4273. fp16_storage = true;
  4274. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4275. fp16_compute = true;
  4276. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4277. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4278. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4279. coopmat_support = true;
  4280. #endif
  4281. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4282. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4283. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4284. coopmat2_support = true;
  4285. #endif
  4286. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4287. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4288. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4289. integer_dot_product = true;
  4290. #endif
  4291. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4292. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4293. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4294. bfloat16_support = true;
  4295. #endif
  4296. }
  4297. }
  4298. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4299. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4300. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4301. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4302. vk::PhysicalDeviceProperties2 props2;
  4303. vk::PhysicalDeviceMaintenance3Properties props3;
  4304. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4305. vk::PhysicalDeviceDriverProperties driver_props;
  4306. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4307. props2.pNext = &props3;
  4308. props3.pNext = &subgroup_props;
  4309. subgroup_props.pNext = &driver_props;
  4310. // Pointer to the last chain element
  4311. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4312. if (integer_dot_product) {
  4313. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4314. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4315. }
  4316. physical_device.getProperties2(&props2);
  4317. VkPhysicalDeviceFeatures2 device_features2;
  4318. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4319. device_features2.pNext = nullptr;
  4320. VkPhysicalDeviceVulkan11Features vk11_features;
  4321. vk11_features.pNext = nullptr;
  4322. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4323. device_features2.pNext = &vk11_features;
  4324. VkPhysicalDeviceVulkan12Features vk12_features;
  4325. vk12_features.pNext = nullptr;
  4326. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4327. vk11_features.pNext = &vk12_features;
  4328. // Pointer to the last chain element
  4329. last_struct = (VkBaseOutStructure *)&vk12_features;
  4330. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4331. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4332. coopmat_features.pNext = nullptr;
  4333. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4334. coopmat_features.cooperativeMatrix = VK_FALSE;
  4335. if (coopmat_support) {
  4336. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4337. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4338. }
  4339. #endif
  4340. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4341. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4342. if (integer_dot_product) {
  4343. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4344. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4345. }
  4346. #if defined(VK_KHR_shader_bfloat16)
  4347. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4348. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4349. if (bfloat16_support) {
  4350. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4351. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4352. }
  4353. #endif
  4354. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4355. fp16 = fp16 && vk12_features.shaderFloat16;
  4356. #if defined(VK_KHR_shader_bfloat16)
  4357. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4358. #else
  4359. bool bf16 = false;
  4360. #endif
  4361. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4362. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4363. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4364. integer_dot_product = integer_dot_product
  4365. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4366. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4367. coopmat_support = coopmat_support
  4368. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4369. && coopmat_features.cooperativeMatrix
  4370. #endif
  4371. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4372. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4373. std::string device_name = props2.properties.deviceName.data();
  4374. GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %d | bf16: %d | warp size: %zu | shared memory: %d | int dot: %d | matrix cores: %s\n",
  4375. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4376. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4377. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4378. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4379. }
  4380. }
  4381. static bool ggml_vk_instance_layer_settings_available();
  4382. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4383. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4384. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4385. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4386. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4387. return ggml_vk_default_dispatcher_instance;
  4388. }
  4389. static void ggml_vk_instance_init() {
  4390. if (vk_instance_initialized) {
  4391. return;
  4392. }
  4393. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4394. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4395. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4396. uint32_t api_version = vk::enumerateInstanceVersion();
  4397. if (api_version < VK_API_VERSION_1_2) {
  4398. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4399. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4400. }
  4401. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4402. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4403. const bool layer_settings = ggml_vk_instance_layer_settings_available();
  4404. #ifdef __APPLE__
  4405. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4406. #endif
  4407. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4408. std::vector<const char*> layers;
  4409. if (layer_settings) {
  4410. layers.push_back("VK_LAYER_KHRONOS_validation");
  4411. }
  4412. std::vector<const char*> extensions;
  4413. if (layer_settings) {
  4414. extensions.push_back("VK_EXT_layer_settings");
  4415. }
  4416. #ifdef __APPLE__
  4417. if (portability_enumeration_ext) {
  4418. extensions.push_back("VK_KHR_portability_enumeration");
  4419. }
  4420. #endif
  4421. if (debug_utils_ext) {
  4422. extensions.push_back("VK_EXT_debug_utils");
  4423. }
  4424. VkBool32 enable_best_practice = layer_settings;
  4425. std::vector<vk::LayerSettingEXT> settings = {
  4426. {
  4427. "VK_LAYER_KHRONOS_validation",
  4428. "validate_best_practices",
  4429. vk::LayerSettingTypeEXT::eBool32,
  4430. 1,
  4431. &enable_best_practice
  4432. },
  4433. };
  4434. vk::LayerSettingsCreateInfoEXT layer_setting_info(settings);
  4435. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions, &layer_setting_info);
  4436. #ifdef __APPLE__
  4437. if (portability_enumeration_ext) {
  4438. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4439. }
  4440. #endif
  4441. vk_instance.instance = vk::createInstance(instance_create_info);
  4442. vk_instance_initialized = true;
  4443. if (debug_utils_ext) {
  4444. vk_instance.debug_utils_support = true;
  4445. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4446. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4447. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4448. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4449. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4450. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4451. }
  4452. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4453. const char* GGML_VK_PERF_LOGGER_FREQUENCY = getenv("GGML_VK_PERF_LOGGER_FREQUENCY");
  4454. if (GGML_VK_PERF_LOGGER_FREQUENCY != nullptr) {
  4455. vk_perf_logger_frequency = std::stoul(GGML_VK_PERF_LOGGER_FREQUENCY);
  4456. }
  4457. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4458. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4459. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4460. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4461. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4462. if (devices_env != nullptr) {
  4463. size_t num_available_devices = devices.size();
  4464. std::string devices(devices_env);
  4465. std::replace(devices.begin(), devices.end(), ',', ' ');
  4466. std::stringstream ss(devices);
  4467. size_t tmp;
  4468. while (ss >> tmp) {
  4469. if(tmp >= num_available_devices) {
  4470. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4471. throw std::runtime_error("Invalid Vulkan device index");
  4472. }
  4473. vk_instance.device_indices.push_back(tmp);
  4474. }
  4475. } else {
  4476. // If no vulkan devices are found, return early
  4477. if (devices.empty()) {
  4478. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4479. return;
  4480. }
  4481. // Default to using all dedicated GPUs
  4482. for (size_t i = 0; i < devices.size(); i++) {
  4483. vk::PhysicalDeviceProperties2 new_props;
  4484. vk::PhysicalDeviceDriverProperties new_driver;
  4485. vk::PhysicalDeviceIDProperties new_id;
  4486. new_props.pNext = &new_driver;
  4487. new_driver.pNext = &new_id;
  4488. devices[i].getProperties2(&new_props);
  4489. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4490. // Check if there are two physical devices corresponding to the same GPU
  4491. auto old_device = std::find_if(
  4492. vk_instance.device_indices.begin(),
  4493. vk_instance.device_indices.end(),
  4494. [&devices, &new_id](const size_t k){
  4495. vk::PhysicalDeviceProperties2 old_props;
  4496. vk::PhysicalDeviceIDProperties old_id;
  4497. old_props.pNext = &old_id;
  4498. devices[k].getProperties2(&old_props);
  4499. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4500. equals = equals || (
  4501. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4502. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4503. );
  4504. return equals;
  4505. }
  4506. );
  4507. if (old_device == vk_instance.device_indices.end()) {
  4508. vk_instance.device_indices.push_back(i);
  4509. } else {
  4510. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4511. // This can cause error when splitting layers aross the devices, need to keep only 1
  4512. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4513. vk::PhysicalDeviceProperties2 old_props;
  4514. vk::PhysicalDeviceDriverProperties old_driver;
  4515. old_props.pNext = &old_driver;
  4516. devices[*old_device].getProperties2(&old_props);
  4517. std::map<vk::DriverId, int> driver_priorities {};
  4518. int old_priority = std::numeric_limits<int>::max();
  4519. int new_priority = std::numeric_limits<int>::max();
  4520. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4521. // Smaller number -> higher priority
  4522. switch (old_props.properties.vendorID) {
  4523. case VK_VENDOR_ID_AMD:
  4524. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4525. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4526. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4527. break;
  4528. case VK_VENDOR_ID_INTEL:
  4529. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4530. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4531. break;
  4532. case VK_VENDOR_ID_NVIDIA:
  4533. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4534. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4535. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4536. #endif
  4537. break;
  4538. }
  4539. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4540. if (driver_priorities.count(old_driver.driverID)) {
  4541. old_priority = driver_priorities[old_driver.driverID];
  4542. }
  4543. if (driver_priorities.count(new_driver.driverID)) {
  4544. new_priority = driver_priorities[new_driver.driverID];
  4545. }
  4546. if (new_priority < old_priority) {
  4547. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4548. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4549. vk_instance.device_indices.push_back(i);
  4550. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4551. }
  4552. else {
  4553. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4554. }
  4555. }
  4556. }
  4557. }
  4558. // If no GPUs found, fall back to the first non-CPU device.
  4559. // If only CPU devices are available, return without devices.
  4560. if (vk_instance.device_indices.empty()) {
  4561. for (size_t i = 0; i < devices.size(); i++) {
  4562. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4563. vk_instance.device_indices.push_back(i);
  4564. break;
  4565. }
  4566. }
  4567. }
  4568. if (vk_instance.device_indices.empty()) {
  4569. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4570. return;
  4571. }
  4572. }
  4573. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4574. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4575. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4576. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4577. bool membudget_supported = false;
  4578. for (const auto & ext : extensionprops) {
  4579. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4580. membudget_supported = true;
  4581. break;
  4582. }
  4583. }
  4584. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4585. ggml_vk_print_gpu_info(i);
  4586. }
  4587. }
  4588. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4589. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4590. ggml_vk_instance_init();
  4591. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4592. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4593. ctx->device = ggml_vk_get_device(idx);
  4594. ctx->semaphore_idx = 0;
  4595. ctx->event_idx = 0;
  4596. ctx->prealloc_size_x = 0;
  4597. ctx->prealloc_size_y = 0;
  4598. ctx->prealloc_size_split_k = 0;
  4599. // Fixed size of 1KB, for deterministic behavior
  4600. ctx->prealloc_size_add_rms_partials = 1024;
  4601. ctx->fence = ctx->device->device.createFence({});
  4602. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4603. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4604. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4605. if (vk_perf_logger_enabled) {
  4606. ctx->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  4607. }
  4608. #ifdef GGML_VULKAN_CHECK_RESULTS
  4609. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4610. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4611. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4612. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4613. #endif
  4614. }
  4615. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4616. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4617. switch (type) {
  4618. case GGML_TYPE_F32:
  4619. case GGML_TYPE_Q4_0:
  4620. case GGML_TYPE_Q4_1:
  4621. case GGML_TYPE_Q5_0:
  4622. case GGML_TYPE_Q5_1:
  4623. case GGML_TYPE_Q8_0:
  4624. case GGML_TYPE_Q2_K:
  4625. case GGML_TYPE_Q3_K:
  4626. case GGML_TYPE_Q4_K:
  4627. case GGML_TYPE_Q5_K:
  4628. case GGML_TYPE_Q6_K:
  4629. case GGML_TYPE_IQ1_S:
  4630. case GGML_TYPE_IQ1_M:
  4631. case GGML_TYPE_IQ2_XXS:
  4632. case GGML_TYPE_IQ2_XS:
  4633. case GGML_TYPE_IQ2_S:
  4634. case GGML_TYPE_IQ3_XXS:
  4635. case GGML_TYPE_IQ3_S:
  4636. case GGML_TYPE_IQ4_XS:
  4637. case GGML_TYPE_IQ4_NL:
  4638. case GGML_TYPE_MXFP4:
  4639. break;
  4640. default:
  4641. return nullptr;
  4642. }
  4643. return ctx->device->pipeline_dequant[type];
  4644. }
  4645. 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) {
  4646. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4647. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4648. return ctx->device->pipeline_matmul_f32;
  4649. }
  4650. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4651. return ctx->device->pipeline_matmul_f32_f16;
  4652. }
  4653. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4654. return ctx->device->pipeline_matmul_bf16;
  4655. }
  4656. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4657. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4658. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4659. }
  4660. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4661. return ctx->device->pipeline_matmul_f16.f16acc;
  4662. }
  4663. } else {
  4664. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4665. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4666. }
  4667. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4668. return ctx->device->pipeline_matmul_f16.f32acc;
  4669. }
  4670. }
  4671. // MMQ
  4672. if (src1_type == GGML_TYPE_Q8_1) {
  4673. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4674. if (pipelines->is_empty()) {
  4675. return nullptr;
  4676. }
  4677. return pipelines;
  4678. }
  4679. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4680. return nullptr;
  4681. }
  4682. switch (src0_type) {
  4683. case GGML_TYPE_Q4_0:
  4684. case GGML_TYPE_Q4_1:
  4685. case GGML_TYPE_Q5_0:
  4686. case GGML_TYPE_Q5_1:
  4687. case GGML_TYPE_Q8_0:
  4688. case GGML_TYPE_Q2_K:
  4689. case GGML_TYPE_Q3_K:
  4690. case GGML_TYPE_Q4_K:
  4691. case GGML_TYPE_Q5_K:
  4692. case GGML_TYPE_Q6_K:
  4693. case GGML_TYPE_IQ1_S:
  4694. case GGML_TYPE_IQ1_M:
  4695. case GGML_TYPE_IQ2_XXS:
  4696. case GGML_TYPE_IQ2_XS:
  4697. case GGML_TYPE_IQ2_S:
  4698. case GGML_TYPE_IQ3_XXS:
  4699. case GGML_TYPE_IQ3_S:
  4700. case GGML_TYPE_IQ4_XS:
  4701. case GGML_TYPE_IQ4_NL:
  4702. case GGML_TYPE_MXFP4:
  4703. break;
  4704. default:
  4705. return nullptr;
  4706. }
  4707. if (ctx->device->coopmat2) {
  4708. assert(src1_type == GGML_TYPE_F16);
  4709. return prec == GGML_PREC_DEFAULT ? ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f32acc;
  4710. }
  4711. if (ctx->device->coopmat_support) {
  4712. return (ctx->device->fp16 && ctx->device->coopmat_acc_f16_support && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  4713. }
  4714. return (ctx->device->fp16 && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  4715. }
  4716. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t num_cols, uint32_t m, uint32_t k) {
  4717. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4718. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4719. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4720. if (b_type == GGML_TYPE_Q8_1) {
  4721. switch (a_type) {
  4722. case GGML_TYPE_Q4_0:
  4723. case GGML_TYPE_Q4_1:
  4724. case GGML_TYPE_Q5_0:
  4725. case GGML_TYPE_Q5_1:
  4726. case GGML_TYPE_Q8_0:
  4727. case GGML_TYPE_MXFP4:
  4728. case GGML_TYPE_Q2_K:
  4729. case GGML_TYPE_Q3_K:
  4730. case GGML_TYPE_Q4_K:
  4731. case GGML_TYPE_Q5_K:
  4732. case GGML_TYPE_Q6_K:
  4733. break;
  4734. default:
  4735. return nullptr;
  4736. }
  4737. }
  4738. switch (a_type) {
  4739. case GGML_TYPE_F32:
  4740. case GGML_TYPE_F16:
  4741. case GGML_TYPE_BF16:
  4742. case GGML_TYPE_Q4_0:
  4743. case GGML_TYPE_Q4_1:
  4744. case GGML_TYPE_Q5_0:
  4745. case GGML_TYPE_Q5_1:
  4746. case GGML_TYPE_Q8_0:
  4747. case GGML_TYPE_Q2_K:
  4748. case GGML_TYPE_Q3_K:
  4749. case GGML_TYPE_Q4_K:
  4750. case GGML_TYPE_Q5_K:
  4751. case GGML_TYPE_Q6_K:
  4752. case GGML_TYPE_IQ1_S:
  4753. case GGML_TYPE_IQ1_M:
  4754. case GGML_TYPE_IQ2_XXS:
  4755. case GGML_TYPE_IQ2_XS:
  4756. case GGML_TYPE_IQ2_S:
  4757. case GGML_TYPE_IQ3_XXS:
  4758. case GGML_TYPE_IQ3_S:
  4759. case GGML_TYPE_IQ4_XS:
  4760. case GGML_TYPE_IQ4_NL:
  4761. case GGML_TYPE_MXFP4:
  4762. break;
  4763. default:
  4764. return nullptr;
  4765. }
  4766. // heuristic to choose workgroup size
  4767. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4768. if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4769. // Prefer larger workgroups when M is small, to spread the work out more
  4770. // and keep more SMs busy.
  4771. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4772. if (a_type == GGML_TYPE_Q6_K) {
  4773. if (m < 4096 && k >= 1024) {
  4774. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4775. }
  4776. } else {
  4777. if (m <= 8192 && k >= 1024) {
  4778. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4779. }
  4780. }
  4781. }
  4782. if (b_type == GGML_TYPE_Q8_1) {
  4783. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4784. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4785. }
  4786. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4787. }
  4788. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[dmmv_wg][a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[dmmv_wg][a_type][num_cols-1];
  4789. }
  4790. 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) {
  4791. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4792. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4793. return ctx->device->pipeline_matmul_id_f32;
  4794. }
  4795. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4796. return ctx->device->pipeline_matmul_id_bf16;
  4797. }
  4798. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4799. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4800. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4801. }
  4802. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4803. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4804. }
  4805. } else {
  4806. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4807. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4808. }
  4809. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4810. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4811. }
  4812. }
  4813. // MMQ
  4814. if (src1_type == GGML_TYPE_Q8_1) {
  4815. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4816. if (pipelines->is_empty()) {
  4817. return nullptr;
  4818. }
  4819. return pipelines;
  4820. }
  4821. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4822. switch (src0_type) {
  4823. case GGML_TYPE_Q4_0:
  4824. case GGML_TYPE_Q4_1:
  4825. case GGML_TYPE_Q5_0:
  4826. case GGML_TYPE_Q5_1:
  4827. case GGML_TYPE_Q8_0:
  4828. case GGML_TYPE_Q2_K:
  4829. case GGML_TYPE_Q3_K:
  4830. case GGML_TYPE_Q4_K:
  4831. case GGML_TYPE_Q5_K:
  4832. case GGML_TYPE_Q6_K:
  4833. case GGML_TYPE_IQ1_S:
  4834. case GGML_TYPE_IQ1_M:
  4835. case GGML_TYPE_IQ2_XXS:
  4836. case GGML_TYPE_IQ2_XS:
  4837. case GGML_TYPE_IQ2_S:
  4838. case GGML_TYPE_IQ3_XXS:
  4839. case GGML_TYPE_IQ3_S:
  4840. case GGML_TYPE_IQ4_XS:
  4841. case GGML_TYPE_IQ4_NL:
  4842. case GGML_TYPE_MXFP4:
  4843. break;
  4844. default:
  4845. return nullptr;
  4846. }
  4847. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4848. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4849. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4850. bool support_fp16acc = !mmp.f16acc->is_empty();
  4851. bool support_fp32acc = !mmp.f32acc->is_empty();
  4852. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4853. return mmp.f16acc;
  4854. } else {
  4855. GGML_ASSERT(support_fp32acc);
  4856. return mmp.f32acc;
  4857. }
  4858. }
  4859. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t m, uint32_t k) {
  4860. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4861. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_Q8_1);
  4862. if (b_type == GGML_TYPE_Q8_1) {
  4863. switch (a_type) {
  4864. case GGML_TYPE_Q4_0:
  4865. case GGML_TYPE_Q4_1:
  4866. case GGML_TYPE_Q5_0:
  4867. case GGML_TYPE_Q5_1:
  4868. case GGML_TYPE_Q8_0:
  4869. case GGML_TYPE_MXFP4:
  4870. case GGML_TYPE_Q2_K:
  4871. case GGML_TYPE_Q3_K:
  4872. case GGML_TYPE_Q4_K:
  4873. case GGML_TYPE_Q5_K:
  4874. case GGML_TYPE_Q6_K:
  4875. break;
  4876. default:
  4877. return nullptr;
  4878. }
  4879. }
  4880. switch (a_type) {
  4881. case GGML_TYPE_F32:
  4882. case GGML_TYPE_F16:
  4883. case GGML_TYPE_BF16:
  4884. case GGML_TYPE_Q4_0:
  4885. case GGML_TYPE_Q4_1:
  4886. case GGML_TYPE_Q5_0:
  4887. case GGML_TYPE_Q5_1:
  4888. case GGML_TYPE_Q8_0:
  4889. case GGML_TYPE_Q2_K:
  4890. case GGML_TYPE_Q3_K:
  4891. case GGML_TYPE_Q4_K:
  4892. case GGML_TYPE_Q5_K:
  4893. case GGML_TYPE_Q6_K:
  4894. case GGML_TYPE_IQ1_S:
  4895. case GGML_TYPE_IQ1_M:
  4896. case GGML_TYPE_IQ2_XXS:
  4897. case GGML_TYPE_IQ2_XS:
  4898. case GGML_TYPE_IQ2_S:
  4899. case GGML_TYPE_IQ3_XXS:
  4900. case GGML_TYPE_IQ3_S:
  4901. case GGML_TYPE_IQ4_XS:
  4902. case GGML_TYPE_IQ4_NL:
  4903. case GGML_TYPE_MXFP4:
  4904. break;
  4905. default:
  4906. return nullptr;
  4907. }
  4908. // heuristic to choose workgroup size
  4909. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4910. if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4911. // Prefer larger workgroups when M is small, to spread the work out more
  4912. // and keep more SMs busy.
  4913. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4914. if (a_type == GGML_TYPE_Q6_K) {
  4915. if (m < 4096 && k >= 1024) {
  4916. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4917. }
  4918. } else {
  4919. if (m <= 8192 && k >= 1024) {
  4920. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4921. }
  4922. }
  4923. }
  4924. if (b_type == GGML_TYPE_Q8_1) {
  4925. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4926. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4927. }
  4928. return ctx->device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[dmmv_wg][a_type];
  4929. }
  4930. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[dmmv_wg][a_type];
  4931. }
  4932. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4933. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4934. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4935. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4936. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4937. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4938. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4939. size/1024.0/1024.0);
  4940. device->device.freeMemory(buf->device_memory);
  4941. device->device.destroyBuffer(buf->buffer);
  4942. return nullptr;
  4943. }
  4944. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4945. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4946. return buf->ptr;
  4947. }
  4948. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4949. if (ptr == nullptr) {
  4950. return;
  4951. }
  4952. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4953. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4954. vk_buffer buf;
  4955. size_t index;
  4956. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4957. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4958. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4959. if (ptr >= addr && ptr < endr) {
  4960. buf = std::get<2>(device->pinned_memory[i]);
  4961. index = i;
  4962. break;
  4963. }
  4964. }
  4965. if (buf == nullptr) {
  4966. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4967. return;
  4968. }
  4969. ggml_vk_destroy_buffer(buf);
  4970. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4971. }
  4972. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4973. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4974. buf = nullptr;
  4975. buf_offset = 0;
  4976. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4977. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4978. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4979. if (ptr >= addr && ptr < endr) {
  4980. buf = std::get<2>(device->pinned_memory[i]);
  4981. buf_offset = ((const uint8_t *)ptr) - addr;
  4982. break;
  4983. }
  4984. }
  4985. }
  4986. static vk_subbuffer ggml_vk_tensor_subbuffer(
  4987. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  4988. vk_buffer buffer = nullptr;
  4989. size_t offset = 0;
  4990. if (ctx->device->uma) {
  4991. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  4992. }
  4993. if (!buffer) {
  4994. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  4995. buffer = buf_ctx->dev_buffer;
  4996. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  4997. }
  4998. GGML_ASSERT(buffer != nullptr);
  4999. size_t size = ggml_nbytes(tensor);
  5000. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  5001. // The shader must support misaligned offsets when indexing into the buffer
  5002. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  5003. offset &= ~misalign_bytes;
  5004. size += misalign_bytes;
  5005. return vk_subbuffer{buffer, offset, size};
  5006. }
  5007. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  5008. vk_submission s;
  5009. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  5010. if (one_time) {
  5011. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  5012. } else {
  5013. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  5014. }
  5015. return s;
  5016. }
  5017. template <typename T> size_t push_constant_size(const T &t) {
  5018. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5019. GGML_UNUSED(t);
  5020. return sizeof(T);
  5021. }
  5022. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  5023. GGML_UNUSED(t);
  5024. return sizeof(T) * t.size();
  5025. }
  5026. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  5027. GGML_UNUSED(t);
  5028. return sizeof(T) * N;
  5029. }
  5030. template <typename T> const T *push_constant_data(const T &t) {
  5031. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5032. return &t;
  5033. }
  5034. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  5035. return t.data();
  5036. }
  5037. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  5038. return t.data();
  5039. }
  5040. template <typename T>
  5041. static void ggml_vk_dispatch_pipeline(ggml_backend_vk_context* ctx, vk_context& subctx, vk_pipeline& pipeline, std::initializer_list<vk::DescriptorBufferInfo> const& descriptor_buffer_infos, const T &push_constants, std::array<uint32_t, 3> elements) {
  5042. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  5043. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  5044. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  5045. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  5046. for (auto& buffer : descriptor_buffer_infos) {
  5047. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  5048. }
  5049. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  5050. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  5051. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  5052. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  5053. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  5054. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  5055. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  5056. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  5057. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  5058. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  5059. pipeline->layout,
  5060. 0,
  5061. { descriptor_set },
  5062. {});
  5063. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  5064. }
  5065. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  5066. s.buffer.end();
  5067. s.wait_semaphores = std::move(wait_semaphores);
  5068. s.signal_semaphores = std::move(signal_semaphores);
  5069. }
  5070. static void ggml_vk_ctx_end(vk_context& ctx) {
  5071. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  5072. if (ctx->s == nullptr) {
  5073. return;
  5074. }
  5075. ctx->s->buffer.end();
  5076. ctx->s = nullptr;
  5077. }
  5078. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  5079. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  5080. if (subctx->s != nullptr) {
  5081. ggml_vk_ctx_end(subctx);
  5082. }
  5083. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  5084. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  5085. }
  5086. static size_t ggml_vk_align_size(size_t width, size_t align) {
  5087. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  5088. return CEIL_DIV(width, align) * align;
  5089. }
  5090. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  5091. if (memcpys == nullptr) {
  5092. memcpy(dst, src, size);
  5093. } else {
  5094. memcpys->emplace_back(dst, src, size);
  5095. }
  5096. }
  5097. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  5098. if (memsets == nullptr) {
  5099. memset(dst, val, size);
  5100. } else {
  5101. memsets->emplace_back(dst, val, size);
  5102. }
  5103. }
  5104. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  5105. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  5106. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5107. ggml_vk_destroy_buffer(device->sync_staging);
  5108. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  5109. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5110. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5111. }
  5112. }
  5113. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  5114. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  5115. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5116. ggml_vk_destroy_buffer(ctx->sync_staging);
  5117. ctx->sync_staging = ggml_vk_create_buffer_check(ctx->device, size,
  5118. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5119. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5120. }
  5121. }
  5122. 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) {
  5123. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  5124. GGML_ASSERT(!ggml_is_contiguous(tensor));
  5125. // Buffer is already mapped
  5126. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5127. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5128. GGML_ABORT("fatal error");
  5129. }
  5130. // Check if src is pinned memory
  5131. vk_buffer buf = nullptr;
  5132. size_t buf_offset = 0;
  5133. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  5134. const uint64_t ne0 = tensor->ne[0];
  5135. const uint64_t ne1 = tensor->ne[1];
  5136. const uint64_t ne2 = tensor->ne[2];
  5137. const uint64_t ne3 = tensor->ne[3];
  5138. const uint64_t nb0 = tensor->nb[0];
  5139. const uint64_t nb1 = tensor->nb[1];
  5140. const uint64_t nb2 = tensor->nb[2];
  5141. const uint64_t nb3 = tensor->nb[3];
  5142. const ggml_type type = tensor->type;
  5143. const uint64_t ts = ggml_type_size(type);
  5144. const uint64_t bs = ggml_blck_size(type);
  5145. const uint64_t dstnb0 = ts;
  5146. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  5147. const uint64_t dstnb2 = dstnb1*ne1;
  5148. const uint64_t dstnb3 = dstnb2*ne2;
  5149. const uint64_t ne = ggml_nelements(tensor);
  5150. if (buf != nullptr) {
  5151. // Memory is pinned, use as staging buffer
  5152. std::vector<vk::BufferCopy> slices;
  5153. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5154. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5155. // Find longest contiguous slice
  5156. if (ne1*nb1 == dstnb2) {
  5157. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  5158. } else {
  5159. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5160. if (ne0*nb0/bs == dstnb1) {
  5161. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  5162. } else {
  5163. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5164. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5165. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5166. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  5167. }
  5168. }
  5169. }
  5170. }
  5171. }
  5172. }
  5173. ggml_vk_sync_buffers(ctx, subctx);
  5174. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5175. return;
  5176. }
  5177. if (!sync_staging) {
  5178. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5179. }
  5180. // Staging buffer required
  5181. vk_buffer& staging = ctx->device->sync_staging;
  5182. const uint64_t copy_size = ts*ne/bs;
  5183. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  5184. VkBufferCopy buf_copy{ 0, offset, copy_size };
  5185. ggml_vk_sync_buffers(ctx, subctx);
  5186. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5187. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5188. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5189. // Find longest contiguous slice
  5190. if (ne1*nb1 == dstnb2) {
  5191. 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);
  5192. } else {
  5193. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5194. if (ne0*nb0/bs == dstnb1) {
  5195. 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);
  5196. } else {
  5197. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5198. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5199. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5200. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  5201. }
  5202. }
  5203. }
  5204. }
  5205. }
  5206. }
  5207. }
  5208. 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) {
  5209. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  5210. // Buffer is already mapped
  5211. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5212. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5213. GGML_ABORT("fatal error");
  5214. }
  5215. // Check if src is pinned memory
  5216. vk_buffer buf = nullptr;
  5217. size_t buf_offset = 0;
  5218. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  5219. if (buf != nullptr) {
  5220. // Memory is pinned, use as staging buffer
  5221. std::vector<vk::BufferCopy> slices(1);
  5222. if (width == spitch) {
  5223. // Only do single write if stride is equal
  5224. slices[0].srcOffset = buf_offset;
  5225. slices[0].dstOffset = offset;
  5226. slices[0].size = width * height;
  5227. } else {
  5228. slices.resize(height);
  5229. for (size_t i = 0; i < height; i++) {
  5230. slices[i].srcOffset = buf_offset + i * spitch;
  5231. slices[i].dstOffset = offset + i * width;
  5232. slices[i].size = width;
  5233. }
  5234. }
  5235. ggml_vk_sync_buffers(nullptr, subctx);
  5236. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5237. return;
  5238. }
  5239. VK_LOG_DEBUG("STAGING");
  5240. if (!sync_staging) {
  5241. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5242. }
  5243. // Staging buffer required
  5244. const size_t copy_size = width*height;
  5245. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  5246. vk_buffer& staging_buffer = dst->device->sync_staging;
  5247. VkBufferCopy buf_copy = {
  5248. 0,
  5249. offset,
  5250. copy_size};
  5251. ggml_vk_sync_buffers(nullptr, subctx);
  5252. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5253. if (width == spitch) {
  5254. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  5255. } else {
  5256. for (size_t i = 0; i < height; i++) {
  5257. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  5258. }
  5259. }
  5260. }
  5261. 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) {
  5262. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  5263. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  5264. }
  5265. 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) {
  5266. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  5267. // Buffer is already mapped
  5268. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5269. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5270. for (size_t i = 0; i < height; i++) {
  5271. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  5272. }
  5273. } else {
  5274. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5275. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5276. ggml_vk_ctx_begin(dst->device, subctx);
  5277. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  5278. ggml_vk_ctx_end(subctx);
  5279. for (auto& cpy : subctx->in_memcpys) {
  5280. memcpy(cpy.dst, cpy.src, cpy.n);
  5281. }
  5282. for (auto& mset : subctx->memsets) {
  5283. memset(mset.dst, mset.val, mset.n);
  5284. }
  5285. ggml_vk_submit(subctx, dst->device->fence);
  5286. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  5287. dst->device->device.resetFences({ dst->device->fence });
  5288. ggml_vk_queue_command_pools_cleanup(dst->device);
  5289. }
  5290. }
  5291. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  5292. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  5293. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  5294. }
  5295. static bool 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) {
  5296. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  5297. GGML_ASSERT(width > 0);
  5298. GGML_ASSERT(height > 0);
  5299. GGML_ASSERT(src != nullptr);
  5300. // TODO: staging_offset is not used
  5301. // Check if dst is pinned memory
  5302. vk_buffer buf = nullptr;
  5303. size_t buf_offset = 0;
  5304. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  5305. std::vector<vk::BufferCopy> slices(1);
  5306. if (width == spitch && width == dpitch) {
  5307. // Only do single write if stride is equal
  5308. slices[0].srcOffset = offset;
  5309. slices[0].dstOffset = buf_offset;
  5310. slices[0].size = width * height;
  5311. } else {
  5312. slices.resize(height);
  5313. for (size_t i = 0; i < height; i++) {
  5314. slices[i].srcOffset = offset + i * spitch;
  5315. slices[i].dstOffset = buf_offset + i * dpitch;
  5316. slices[i].size = width;
  5317. }
  5318. }
  5319. if (buf != nullptr) {
  5320. // Memory is pinned, use as staging buffer
  5321. ggml_vk_sync_buffers(nullptr, subctx);
  5322. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5323. return true;
  5324. }
  5325. VK_LOG_DEBUG("STAGING");
  5326. if (!sync_staging) {
  5327. // copy was not handled caller needs to fall back
  5328. return false;
  5329. }
  5330. // Fall back to staging buffer
  5331. const size_t copy_size = dpitch * height;
  5332. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5333. vk_buffer& staging_buffer = src->device->sync_staging;
  5334. ggml_vk_sync_buffers(nullptr, subctx);
  5335. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5336. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5337. return true;
  5338. }
  5339. static bool ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  5340. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5341. }
  5342. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5343. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5344. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5345. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5346. // the HW device to host copy path.
  5347. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5348. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5349. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5350. } else {
  5351. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5352. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5353. ggml_vk_ctx_begin(src->device, subctx);
  5354. bool ret = ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5355. GGML_ASSERT(ret);
  5356. ggml_vk_ctx_end(subctx);
  5357. ggml_vk_submit(subctx, src->device->fence);
  5358. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5359. src->device->device.resetFences({ src->device->fence });
  5360. ggml_vk_queue_command_pools_cleanup(src->device);
  5361. for (auto& cpy : subctx->out_memcpys) {
  5362. memcpy(cpy.dst, cpy.src, cpy.n);
  5363. }
  5364. }
  5365. }
  5366. 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) {
  5367. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5368. // Make sure both buffers are on same device
  5369. GGML_ASSERT(src->device == dst->device);
  5370. VkBufferCopy bc{ src_offset, dst_offset, size };
  5371. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5372. }
  5373. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5374. if (src->device == dst->device) {
  5375. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5376. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5377. // Copy within the device
  5378. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5379. ggml_vk_ctx_begin(src->device, subctx);
  5380. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5381. ggml_vk_ctx_end(subctx);
  5382. ggml_vk_submit(subctx, src->device->fence);
  5383. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5384. src->device->device.resetFences({ src->device->fence });
  5385. ggml_vk_queue_command_pools_cleanup(src->device);
  5386. } else {
  5387. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5388. // Copy device to device
  5389. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5390. // Copy to src staging buffer
  5391. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5392. // Copy to dst buffer
  5393. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5394. }
  5395. }
  5396. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5397. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5398. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5399. dst->device->uma) {
  5400. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5401. return;
  5402. }
  5403. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5404. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5405. }
  5406. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5407. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5408. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5409. dst->device->uma) {
  5410. memset((uint8_t*)dst->ptr + offset, c, size);
  5411. return;
  5412. }
  5413. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5414. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5415. ggml_vk_ctx_begin(dst->device, subctx);
  5416. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5417. ggml_vk_ctx_end(subctx);
  5418. ggml_vk_submit(subctx, dst->device->fence);
  5419. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5420. dst->device->device.resetFences({ dst->device->fence });
  5421. ggml_vk_queue_command_pools_cleanup(dst->device);
  5422. }
  5423. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, bool disable_split_k, const vk_pipeline& pipeline) {
  5424. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5425. if (disable_split_k) {
  5426. return 1;
  5427. }
  5428. uint32_t split_k = 1;
  5429. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5430. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5431. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5432. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5433. if (k >= 2048) {
  5434. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5435. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5436. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5437. split_k = 3;
  5438. }
  5439. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5440. split_k = std::min(split_k, 8u);
  5441. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5442. // If this rounded up size would cause the last split to be empty,
  5443. // then reduce the split count.
  5444. while (true) {
  5445. if (split_k == 1) {
  5446. break;
  5447. }
  5448. uint32_t k_split = CEIL_DIV(k, split_k);
  5449. k_split = ROUNDUP_POW2(k_split, 256);
  5450. if (k_split * (split_k - 1) < k) {
  5451. break;
  5452. }
  5453. split_k--;
  5454. }
  5455. }
  5456. }
  5457. return split_k;
  5458. }
  5459. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, uint32_t m, uint32_t n, bool aligned, ggml_type src0_type, ggml_type src1_type) {
  5460. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5461. if (ctx->device->coopmat2) {
  5462. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5463. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5464. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5465. // Use large shader when the N dimension is greater than the medium shader's tile size
  5466. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5467. // Prefer large over medium if either:
  5468. // - medium or large tiles would overfill the GPU
  5469. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5470. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5471. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5472. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5473. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5474. if ((ctx->device->mul_mat_l[src0_type] && (n > crossover_large && prefer_large)) || (!ctx->device->mul_mat_m[src0_type] && !ctx->device->mul_mat_s[src0_type])) {
  5475. return aligned ? mmp->a_l : mmp->l;
  5476. }
  5477. // Use medium shader when the N dimension is greater than the small shader's tile size
  5478. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5479. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5480. return aligned ? mmp->a_m : mmp->m;
  5481. }
  5482. return aligned ? mmp->a_s : mmp->s;
  5483. }
  5484. if ((ctx->device->mul_mat_s[src0_type] && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_m[src0_type] && !ctx->device->mul_mat_l[src0_type])) {
  5485. return aligned ? mmp->a_s : mmp->s;
  5486. }
  5487. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5488. return aligned ? mmp->a_m : mmp->m;
  5489. }
  5490. return aligned ? mmp->a_l : mmp->l;
  5491. GGML_UNUSED(src1_type);
  5492. }
  5493. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type src0_type, ggml_type src1_type) {
  5494. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5495. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5496. }
  5497. static void ggml_vk_matmul(
  5498. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5499. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5500. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5501. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5502. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5503. uint32_t padded_n) {
  5504. VK_LOG_DEBUG("ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << (split_k_buffer.buffer != nullptr ? split_k_buffer.buffer->buffer : VK_NULL_HANDLE) << ", " << split_k_buffer.offset << ", " << split_k_buffer.size << "), m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ", padded_n: " << padded_n << ")");
  5505. if (split_k == 1) {
  5506. const vk_mat_mat_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, k, ne02, ne12, broadcast2, broadcast3, padded_n };
  5507. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5508. return;
  5509. }
  5510. if (ctx->prealloc_split_k_need_sync) {
  5511. ggml_vk_sync_buffers(ctx, subctx);
  5512. }
  5513. GGML_ASSERT(batch_stride_d == m * n);
  5514. // Round the split size up to a multiple of 256 (k-quant alignment)
  5515. uint32_t k_split = CEIL_DIV(k, split_k);
  5516. k_split = ROUNDUP_POW2(k_split, 256);
  5517. const vk_mat_mat_push_constants pc1 = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, k_split, ne02, ne12, broadcast2, broadcast3, padded_n };
  5518. // Make sure enough workgroups get assigned for split k to work
  5519. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  5520. ggml_vk_sync_buffers(ctx, subctx);
  5521. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5522. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5523. ctx->prealloc_split_k_need_sync = true;
  5524. }
  5525. static vk_pipeline ggml_vk_guess_matmul_id_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, uint32_t m, uint32_t n, bool aligned, ggml_type src0_type) {
  5526. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5527. if (ctx->device->coopmat2) {
  5528. // Use large shader when the N dimension is greater than the medium shader's tile size
  5529. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5530. if ((ctx->device->mul_mat_id_l[src0_type] && (n > crossover_large)) || (!ctx->device->mul_mat_id_m[src0_type] && !ctx->device->mul_mat_id_s[src0_type])) {
  5531. return aligned ? mmp->a_l : mmp->l;
  5532. }
  5533. // Use medium shader when the N dimension is greater than the small shader's tile size
  5534. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5535. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5536. return aligned ? mmp->a_m : mmp->m;
  5537. }
  5538. return aligned ? mmp->a_s : mmp->s;
  5539. }
  5540. if ((ctx->device->mul_mat_id_s[src0_type] && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_id_m[src0_type] && !ctx->device->mul_mat_id_l[src0_type])) {
  5541. return aligned ? mmp->a_s : mmp->s;
  5542. }
  5543. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5544. return aligned ? mmp->a_m : mmp->m;
  5545. }
  5546. return aligned ? mmp->a_l : mmp->l;
  5547. }
  5548. static uint32_t ggml_vk_guess_matmul_id_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type src0_type) {
  5549. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5550. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5551. }
  5552. static void ggml_vk_matmul_id(
  5553. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5554. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5555. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5556. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5557. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5558. uint32_t padded_n) {
  5559. 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 << "), " <<
  5560. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5561. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5562. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5563. 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,
  5564. nei0, nei1, nbi1, ne11, padded_n };
  5565. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5566. }
  5567. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5568. return
  5569. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5570. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5571. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5572. }
  5573. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5574. // Choose "contiguous copy" shader if src/dst are contiguous
  5575. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5576. // Use optimized "transpose" shader if src dim1 is the innermost dimension.
  5577. bool transpose = dst && src->nb[1] == ggml_type_size(to) && ggml_are_same_shape(dst, src);
  5578. if (transpose && src->type == to) {
  5579. if (ggml_type_size(to) == 4) {
  5580. return ctx->device->pipeline_cpy_transpose_32;
  5581. } else if (ggml_type_size(to) == 2) {
  5582. return ctx->device->pipeline_cpy_transpose_16;
  5583. }
  5584. }
  5585. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5586. if (contig) {
  5587. return ctx->device->pipeline_contig_cpy_f32_f32;
  5588. } else {
  5589. return ctx->device->pipeline_cpy_f32_f32;
  5590. }
  5591. }
  5592. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5593. if (contig) {
  5594. return ctx->device->pipeline_contig_cpy_f32_f16;
  5595. } else {
  5596. return ctx->device->pipeline_cpy_f32_f16;
  5597. }
  5598. }
  5599. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5600. if (contig) {
  5601. return ctx->device->pipeline_contig_cpy_f16_f16;
  5602. } else {
  5603. return ctx->device->pipeline_cpy_f16_f16;
  5604. }
  5605. }
  5606. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5607. if (contig) {
  5608. return ctx->device->pipeline_contig_cpy_f16_f32;
  5609. } else {
  5610. return ctx->device->pipeline_cpy_f16_f32;
  5611. }
  5612. }
  5613. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5614. if (contig) {
  5615. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5616. } else {
  5617. return ctx->device->pipeline_cpy_f32_bf16;
  5618. }
  5619. }
  5620. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5621. if (contig) {
  5622. return ctx->device->pipeline_contig_cpy_f32_i32;
  5623. } else {
  5624. return ctx->device->pipeline_cpy_f32_i32;
  5625. }
  5626. }
  5627. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5628. if (contig) {
  5629. return ctx->device->pipeline_contig_cpy_i32_f32;
  5630. } else {
  5631. return ctx->device->pipeline_cpy_i32_f32;
  5632. }
  5633. }
  5634. if (src->type == GGML_TYPE_F32) {
  5635. switch (to) {
  5636. case GGML_TYPE_Q4_0:
  5637. case GGML_TYPE_Q4_1:
  5638. case GGML_TYPE_Q5_0:
  5639. case GGML_TYPE_Q5_1:
  5640. case GGML_TYPE_Q8_0:
  5641. case GGML_TYPE_IQ4_NL:
  5642. return ctx->device->pipeline_cpy_f32_quant[to];
  5643. default:
  5644. break;
  5645. }
  5646. }
  5647. if (to == GGML_TYPE_F32) {
  5648. switch (src->type) {
  5649. case GGML_TYPE_Q4_0:
  5650. case GGML_TYPE_Q4_1:
  5651. case GGML_TYPE_Q5_0:
  5652. case GGML_TYPE_Q5_1:
  5653. case GGML_TYPE_Q8_0:
  5654. case GGML_TYPE_IQ4_NL:
  5655. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5656. default:
  5657. break;
  5658. }
  5659. }
  5660. if (src->type == to) {
  5661. // Copy two or four bytes at a time, depending on block size.
  5662. // For quantized types, we scale by block size/type size. But
  5663. // this path is also used for bf16->bf16 for example, where the
  5664. // type size must be exactly 2 or 4.
  5665. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5666. if ((ggml_type_size(src->type) % 4) == 0) {
  5667. if (contig) {
  5668. return ctx->device->pipeline_contig_cpy_f32_f32;
  5669. } else {
  5670. return ctx->device->pipeline_cpy_f32_f32;
  5671. }
  5672. } else {
  5673. if (contig) {
  5674. return ctx->device->pipeline_contig_cpy_f16_f16;
  5675. } else {
  5676. return ctx->device->pipeline_cpy_f16_f16;
  5677. }
  5678. }
  5679. }
  5680. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5681. GGML_ABORT("fatal error");
  5682. }
  5683. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, const vk_subbuffer & in, const vk_subbuffer & out) {
  5684. 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] << "), ";
  5685. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5686. const int tensor_type_size = ggml_type_size(tensor->type);
  5687. const uint32_t ne = ggml_nelements(tensor);
  5688. std::array<uint32_t, 3> elements;
  5689. if (ne > 262144) {
  5690. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5691. } else if (ne > 512) {
  5692. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5693. } else {
  5694. elements = { ne, 1, 1 };
  5695. }
  5696. vk_op_unary_push_constants pc = {
  5697. (uint32_t)ne,
  5698. (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,
  5699. (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]),
  5700. 0,
  5701. 0.0f, 0.0f,
  5702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5703. };
  5704. init_pushconst_fastdiv(pc);
  5705. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5706. ggml_vk_sync_buffers(ctx, subctx);
  5707. }
  5708. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5709. switch(type) {
  5710. case GGML_TYPE_Q8_1:
  5711. return ctx->device->pipeline_quantize_q8_1_x4;
  5712. default:
  5713. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5714. GGML_ABORT("fatal error");
  5715. }
  5716. }
  5717. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer & in, const vk_subbuffer & out, uint32_t ne) {
  5718. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5719. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5720. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5721. ggml_vk_sync_buffers(ctx, subctx);
  5722. }
  5723. static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool disable_split_k) {
  5724. VK_LOG_DEBUG("ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << ggml_type_name(src0->type) << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  5725. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << ggml_type_name(src1->type) << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  5726. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << ggml_type_name(dst->type) << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  5727. std::cerr << "))");
  5728. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5729. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5730. const uint64_t ne00 = src0->ne[0];
  5731. const uint64_t ne01 = src0->ne[1];
  5732. const uint64_t ne02 = src0->ne[2];
  5733. const uint64_t ne03 = src0->ne[3];
  5734. const uint64_t ne10 = src1->ne[0];
  5735. const uint64_t ne11 = src1->ne[1];
  5736. const uint64_t ne12 = src1->ne[2];
  5737. const uint64_t ne13 = src1->ne[3];
  5738. const uint64_t ne21 = dst->ne[1];
  5739. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5740. const uint32_t stride_batch_d = stride_d*ne21;
  5741. const uint64_t r2 = ne12 / ne02;
  5742. const uint64_t r3 = ne13 / ne03;
  5743. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5744. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5745. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5746. vk_buffer d_Qx = nullptr;
  5747. size_t qx_buf_offset = 0;
  5748. vk_buffer d_Qy = nullptr;
  5749. size_t qy_buf_offset = 0;
  5750. bool src0_uma = false;
  5751. bool src1_uma = false;
  5752. if (ctx->device->uma) {
  5753. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5754. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5755. src0_uma = d_Qx != nullptr;
  5756. src1_uma = d_Qy != nullptr;
  5757. }
  5758. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5759. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5760. !ggml_vk_dim01_contiguous(src0);
  5761. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5762. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5763. !ggml_vk_dim01_contiguous(src1);
  5764. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5765. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5766. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5767. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  5768. // Check for mmq first
  5769. vk_matmul_pipeline mmp = quantize_y ? ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, GGML_TYPE_Q8_1, (ggml_prec)dst->op_params[0]) : nullptr;
  5770. if (mmp == nullptr) {
  5771. // Fall back to f16 dequant mul mat
  5772. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5773. quantize_y = false;
  5774. }
  5775. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5776. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5777. if (qx_needs_dequant) {
  5778. // Fall back to dequant + f16 mulmat
  5779. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, f16_type, y_f32_kernel ? GGML_TYPE_F32 : f16_type, (ggml_prec)dst->op_params[0]);
  5780. }
  5781. // Not implemented
  5782. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5783. const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11, qx_needs_dequant ? f16_type : src0->type, quantize_y ? GGML_TYPE_Q8_1 : (y_f32_kernel ? GGML_TYPE_F32 : src1->type)));
  5784. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5785. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned, qx_needs_dequant ? f16_type : src0->type, quantize_y ? GGML_TYPE_Q8_1 : (y_f32_kernel ? GGML_TYPE_F32 : src1->type));
  5786. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5787. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5788. const uint64_t x_ne = ggml_nelements(src0);
  5789. // 128 elements per Q8_1 x4 block
  5790. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  5791. const uint64_t d_ne = ggml_nelements(dst);
  5792. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5793. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5794. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5795. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5796. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5797. const uint64_t d_sz = sizeof(float) * d_ne;
  5798. vk_pipeline to_fp16_vk_0 = nullptr;
  5799. vk_pipeline to_fp16_vk_1 = nullptr;
  5800. vk_pipeline to_q8_1 = nullptr;
  5801. if (x_non_contig) {
  5802. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5803. } else {
  5804. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5805. }
  5806. if (y_non_contig) {
  5807. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5808. } else {
  5809. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5810. }
  5811. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5812. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5813. if (quantize_y) {
  5814. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5815. }
  5816. {
  5817. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  5818. if (
  5819. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5820. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5821. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5822. GGML_ABORT("Requested preallocation size is too large");
  5823. }
  5824. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5825. ctx->prealloc_size_x = x_sz;
  5826. ggml_vk_preallocate_buffers(ctx, subctx);
  5827. }
  5828. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5829. ctx->prealloc_size_y = y_sz;
  5830. ggml_vk_preallocate_buffers(ctx, subctx);
  5831. }
  5832. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5833. ctx->prealloc_size_split_k = split_k_size;
  5834. ggml_vk_preallocate_buffers(ctx, subctx);
  5835. }
  5836. // Request descriptor sets
  5837. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5838. if (qx_needs_dequant) {
  5839. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5840. }
  5841. if (qy_needs_dequant) {
  5842. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5843. }
  5844. if (quantize_y) {
  5845. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5846. }
  5847. if (split_k > 1) {
  5848. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5849. }
  5850. }
  5851. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5852. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5853. GGML_ASSERT(d_D != nullptr);
  5854. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  5855. vk_buffer d_X;
  5856. uint64_t x_buf_offset = 0;
  5857. vk_buffer d_Y;
  5858. uint64_t y_buf_offset = 0;
  5859. if (!src0_uma) {
  5860. d_Qx = src0_buf_ctx->dev_buffer;
  5861. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5862. GGML_ASSERT(d_Qx != nullptr);
  5863. }
  5864. if (!src1_uma) {
  5865. d_Qy = src1_buf_ctx->dev_buffer;
  5866. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5867. GGML_ASSERT(d_Qy != nullptr);
  5868. }
  5869. if (qx_needs_dequant) {
  5870. d_X = ctx->prealloc_x;
  5871. GGML_ASSERT(d_X->size >= x_sz);
  5872. } else {
  5873. d_X = d_Qx;
  5874. x_buf_offset = qx_buf_offset;
  5875. GGML_ASSERT(qx_sz == x_sz);
  5876. }
  5877. if (qy_needs_dequant) {
  5878. d_Y = ctx->prealloc_y;
  5879. GGML_ASSERT(d_Y->size >= y_sz);
  5880. } else if (quantize_y) {
  5881. d_Y = ctx->prealloc_y;
  5882. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  5883. } else {
  5884. d_Y = d_Qy;
  5885. y_buf_offset = qy_buf_offset;
  5886. GGML_ASSERT(qy_sz == y_sz);
  5887. }
  5888. if (x_non_contig || qx_needs_dequant) {
  5889. if (ctx->prealloc_x_need_sync) {
  5890. ggml_vk_sync_buffers(ctx, subctx);
  5891. }
  5892. }
  5893. if (x_non_contig) {
  5894. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  5895. } else if (qx_needs_dequant) {
  5896. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5897. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)(x_ne), 1, 1});
  5898. ggml_vk_sync_buffers(ctx, subctx);
  5899. }
  5900. if (y_non_contig) {
  5901. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5902. ctx->prealloc_y_last_tensor_used != src1) {
  5903. if (ctx->prealloc_y_need_sync) {
  5904. ggml_vk_sync_buffers(ctx, subctx);
  5905. }
  5906. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  5907. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5908. ctx->prealloc_y_last_tensor_used = src1;
  5909. }
  5910. }
  5911. if (quantize_y) {
  5912. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5913. ctx->prealloc_y_last_tensor_used != src1) {
  5914. if (ctx->prealloc_y_need_sync) {
  5915. ggml_vk_sync_buffers(ctx, subctx);
  5916. }
  5917. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne);
  5918. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5919. ctx->prealloc_y_last_tensor_used = src1;
  5920. }
  5921. }
  5922. uint32_t stride_batch_x = ne00*ne01;
  5923. uint32_t stride_batch_y = ne10*ne11;
  5924. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5925. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5926. }
  5927. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5928. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5929. }
  5930. // compute
  5931. ggml_vk_matmul(
  5932. ctx, subctx, pipeline,
  5933. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  5934. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  5935. ne01, ne11, ne10,
  5936. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5937. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5938. ); // NOLINT
  5939. if (x_non_contig || qx_needs_dequant) {
  5940. ctx->prealloc_x_need_sync = true;
  5941. }
  5942. if (y_non_contig || quantize_y) {
  5943. ctx->prealloc_y_need_sync = true;
  5944. }
  5945. }
  5946. // Device tuning
  5947. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5948. if (device->mmvq_mode == 1) {
  5949. return true;
  5950. } else if (device->mmvq_mode == -1) {
  5951. return false;
  5952. }
  5953. // General performance issue with q3_k and q6_k due to 2-byte alignment
  5954. if (src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_Q6_K) {
  5955. return false;
  5956. }
  5957. // MMVQ is generally good for batches
  5958. if (n > 1) {
  5959. return true;
  5960. }
  5961. // Quantization overhead is not worth it for small k
  5962. switch (device->vendor_id) {
  5963. case VK_VENDOR_ID_NVIDIA:
  5964. if (src0_type == GGML_TYPE_Q2_K) {
  5965. return true;
  5966. }
  5967. if (k <= 4096) {
  5968. return false;
  5969. }
  5970. switch (src0_type) {
  5971. case GGML_TYPE_MXFP4:
  5972. case GGML_TYPE_Q8_0:
  5973. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5974. default:
  5975. return true;
  5976. }
  5977. case VK_VENDOR_ID_AMD:
  5978. if (k < 2048) {
  5979. return false;
  5980. }
  5981. switch (src0_type) {
  5982. case GGML_TYPE_Q8_0:
  5983. return device->architecture == vk_device_architecture::AMD_GCN;
  5984. default:
  5985. return true;
  5986. }
  5987. case VK_VENDOR_ID_INTEL:
  5988. if (k < 2048) {
  5989. return false;
  5990. }
  5991. switch (src0_type) {
  5992. // From tests on A770 Linux, may need more tuning
  5993. case GGML_TYPE_Q4_0:
  5994. case GGML_TYPE_Q5_1:
  5995. return false;
  5996. default:
  5997. return true;
  5998. }
  5999. default:
  6000. return true;
  6001. }
  6002. GGML_UNUSED(m);
  6003. }
  6004. static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6005. ggml_tensor * dst = cgraph->nodes[node_idx];
  6006. const ggml_tensor * src0 = dst->src[0];
  6007. const ggml_tensor * src1 = dst->src[1];
  6008. 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];
  6009. 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];
  6010. 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];
  6011. std::cerr << ")),)");
  6012. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6013. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6014. const uint64_t ne00 = src0->ne[0];
  6015. const uint64_t ne01 = src0->ne[1];
  6016. const uint64_t ne02 = src0->ne[2];
  6017. const uint64_t ne03 = src0->ne[3];
  6018. const uint64_t ne10 = src1->ne[0];
  6019. const uint64_t ne11 = src1->ne[1];
  6020. const uint64_t ne12 = src1->ne[2];
  6021. const uint64_t ne13 = src1->ne[3];
  6022. const uint64_t ne20 = dst->ne[0];
  6023. const uint64_t ne21 = dst->ne[1];
  6024. // const uint64_t ne22 = dst->ne[2];
  6025. // const uint64_t ne23 = dst->ne[3];
  6026. const uint64_t r2 = ne12 / ne02;
  6027. const uint64_t r3 = ne13 / ne03;
  6028. // batch_n indicates that we need to compute a few vector results, and this assumes
  6029. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  6030. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  6031. bool batch_n = ne11 > 1;
  6032. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6033. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6034. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6035. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  6036. vk_pipeline to_fp16_vk_0 = nullptr;
  6037. vk_pipeline to_fp16_vk_1 = nullptr;
  6038. if (x_non_contig) {
  6039. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6040. }
  6041. if (y_non_contig) {
  6042. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6043. } else {
  6044. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6045. }
  6046. // Check for mmq first
  6047. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  6048. vk_pipeline to_q8_1 = nullptr;
  6049. if (dmmv == nullptr) {
  6050. // Fall back to f16 dequant mul mat
  6051. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  6052. quantize_y = false;
  6053. }
  6054. if (quantize_y) {
  6055. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6056. }
  6057. const bool qx_needs_dequant = x_non_contig;
  6058. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6059. // Not implemented
  6060. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6061. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6062. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6063. GGML_ASSERT(dmmv != nullptr);
  6064. const uint64_t x_ne = ggml_nelements(src0);
  6065. const uint64_t y_ne = ggml_nelements(src1);
  6066. 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);
  6067. 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;
  6068. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) :
  6069. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6070. {
  6071. if (
  6072. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6073. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6074. GGML_ABORT("Requested preallocation size is too large");
  6075. }
  6076. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6077. ctx->prealloc_size_x = x_sz;
  6078. ggml_vk_preallocate_buffers(ctx, subctx);
  6079. }
  6080. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6081. ctx->prealloc_size_y = y_sz;
  6082. ggml_vk_preallocate_buffers(ctx, subctx);
  6083. }
  6084. // Request descriptor sets
  6085. if (qx_needs_dequant) {
  6086. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6087. }
  6088. if (qy_needs_dequant) {
  6089. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6090. }
  6091. if (quantize_y) {
  6092. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6093. }
  6094. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6095. }
  6096. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6097. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6098. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6099. vk_subbuffer d_X, d_Y;
  6100. if (qx_needs_dequant) {
  6101. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6102. } else {
  6103. d_X = d_Qx;
  6104. GGML_ASSERT(qx_sz == x_sz);
  6105. }
  6106. if (qy_needs_dequant || quantize_y) {
  6107. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6108. } else {
  6109. d_Y = d_Qy;
  6110. }
  6111. if (x_non_contig) {
  6112. if (ctx->prealloc_x_need_sync) {
  6113. ggml_vk_sync_buffers(ctx, subctx);
  6114. }
  6115. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6116. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6117. }
  6118. if (y_non_contig) {
  6119. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6120. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6121. ctx->prealloc_y_last_tensor_used != src1) {
  6122. if (ctx->prealloc_y_need_sync) {
  6123. ggml_vk_sync_buffers(ctx, subctx);
  6124. }
  6125. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6126. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6127. ctx->prealloc_y_last_tensor_used = src1;
  6128. }
  6129. }
  6130. if (quantize_y) {
  6131. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6132. ctx->prealloc_y_last_tensor_used != src1) {
  6133. if (ctx->prealloc_y_need_sync) {
  6134. ggml_vk_sync_buffers(ctx, subctx);
  6135. }
  6136. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6137. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6138. ctx->prealloc_y_last_tensor_used = src1;
  6139. }
  6140. }
  6141. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  6142. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  6143. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  6144. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  6145. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6146. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6147. }
  6148. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6149. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6150. }
  6151. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6152. uint32_t groups_x = ne01;
  6153. uint32_t groups_z = 1;
  6154. if (ne01 > max_groups_x) {
  6155. groups_z = 64;
  6156. groups_x = CEIL_DIV(groups_x, groups_z);
  6157. }
  6158. uint32_t fusion_flags = 0;
  6159. vk_subbuffer d_F0 = d_D;
  6160. if (ctx->num_additional_fused_ops > 0) {
  6161. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6162. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6163. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6164. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6165. }
  6166. vk_subbuffer d_F1 = d_D;
  6167. if (ctx->num_additional_fused_ops == 2) {
  6168. const ggml_tensor * add = cgraph->nodes[node_idx + 2];
  6169. const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0];
  6170. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6171. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6172. }
  6173. // compute
  6174. const vk_mat_vec_push_constants pc = {
  6175. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6176. stride_batch_x, stride_batch_y, stride_batch_d,
  6177. fusion_flags,
  6178. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  6179. };
  6180. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6181. {
  6182. d_X,
  6183. d_Y,
  6184. d_D,
  6185. d_F0,
  6186. d_F1,
  6187. },
  6188. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  6189. if (x_non_contig) {
  6190. ctx->prealloc_x_need_sync = true;
  6191. }
  6192. if (y_non_contig || quantize_y) {
  6193. ctx->prealloc_y_need_sync = true;
  6194. }
  6195. }
  6196. static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6197. ggml_tensor * dst = cgraph->nodes[node_idx];
  6198. const ggml_tensor * src0 = dst->src[0];
  6199. const ggml_tensor * src1 = dst->src[1];
  6200. 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];
  6201. 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];
  6202. 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];
  6203. std::cerr << "))");
  6204. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  6205. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  6206. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  6207. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6208. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6209. const uint64_t ne00 = src0->ne[0];
  6210. const uint64_t ne01 = src0->ne[1];
  6211. const uint64_t ne02 = src0->ne[2];
  6212. // const uint64_t ne03 = src0->ne[3];
  6213. //const uint64_t ne10 = src1->ne[0];
  6214. const uint64_t ne11 = src1->ne[1];
  6215. const uint64_t ne12 = src1->ne[2];
  6216. // const uint64_t ne13 = src1->ne[3];
  6217. GGML_ASSERT(ne11 == 1);
  6218. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  6219. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  6220. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  6221. gqa_ratio = 1;
  6222. }
  6223. {
  6224. // Request descriptor sets
  6225. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  6226. }
  6227. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6228. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6229. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6230. vk_subbuffer d_F0 = d_D;
  6231. uint32_t fusion_flags = 0;
  6232. if (ctx->num_additional_fused_ops > 0) {
  6233. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6234. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6235. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6236. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6237. }
  6238. vk_subbuffer d_F1 = d_D;
  6239. if (ctx->num_additional_fused_ops > 1) {
  6240. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6241. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6242. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6243. }
  6244. // compute
  6245. vk_mat_vec_p021_push_constants pc = {
  6246. (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12,
  6247. 0, 0, fusion_flags
  6248. };
  6249. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6250. uint32_t workgroups_z = (uint32_t)ne12;
  6251. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  6252. if (gqa_ratio > 1) {
  6253. workgroups_z /= gqa_ratio;
  6254. }
  6255. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6256. {
  6257. d_Qx,
  6258. d_Qy,
  6259. d_D,
  6260. d_F0,
  6261. d_F1,
  6262. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6263. }
  6264. static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6265. ggml_tensor * dst = cgraph->nodes[node_idx];
  6266. const ggml_tensor * src0 = dst->src[0];
  6267. const ggml_tensor * src1 = dst->src[1];
  6268. 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];
  6269. 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];
  6270. 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];
  6271. std::cerr << "))");
  6272. GGML_ASSERT(!ggml_is_transposed(src0));
  6273. GGML_ASSERT(!ggml_is_transposed(src1));
  6274. GGML_ASSERT(!ggml_is_permuted(src0));
  6275. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6276. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6277. const uint64_t ne00 = src0->ne[0];
  6278. const uint64_t ne01 = src0->ne[1];
  6279. const uint64_t ne02 = src0->ne[2];
  6280. const uint64_t ne03 = src0->ne[3];
  6281. const uint64_t nb01 = src0->nb[1];
  6282. const uint64_t nb02 = src0->nb[2];
  6283. const uint64_t nb12 = src1->nb[2];
  6284. // const uint64_t ne10 = src1->ne[0];
  6285. const uint64_t ne11 = src1->ne[1];
  6286. const uint64_t ne12 = src1->ne[2];
  6287. // const uint64_t ne13 = src1->ne[3];
  6288. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6289. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6290. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6291. GGML_ASSERT(ne11 == 1);
  6292. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6293. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6294. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6295. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6296. {
  6297. // Request descriptor sets
  6298. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6299. }
  6300. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6301. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6302. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6303. vk_subbuffer d_F0 = d_D;
  6304. uint32_t fusion_flags = 0;
  6305. if (ctx->num_additional_fused_ops > 0) {
  6306. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6307. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6308. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6309. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6310. }
  6311. vk_subbuffer d_F1 = d_D;
  6312. if (ctx->num_additional_fused_ops > 1) {
  6313. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6314. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6315. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6316. }
  6317. // compute
  6318. vk_mat_vec_nc_push_constants pc = {
  6319. (uint32_t)ne00, (uint32_t)ne01,
  6320. row_stride_x, channel_stride_x, channel_stride_y,
  6321. (uint32_t)(ne12 / ne02), (uint32_t)ne12,
  6322. 0, 0,
  6323. nb03, nb13, nb23, fusion_flags
  6324. };
  6325. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6326. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6327. {
  6328. d_Qx,
  6329. d_Qy,
  6330. d_D,
  6331. d_F0,
  6332. d_F1,
  6333. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6334. }
  6335. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6336. ggml_tensor * dst = cgraph->nodes[node_idx];
  6337. ggml_tensor * src0 = dst->src[0];
  6338. ggml_tensor * src1 = dst->src[1];
  6339. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6340. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6341. // where the M dimension is very large.
  6342. // Split_k doesn't work with M splitting.
  6343. const size_t nbytes = ggml_nbytes(src0);
  6344. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6345. if (needs_split) {
  6346. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6347. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6348. uint32_t m_offset = 0;
  6349. while (m_offset < dst->ne[0]) {
  6350. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6351. ggml_tensor dst2 = *dst;
  6352. ggml_tensor src02 = *src0;
  6353. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6354. src02.view_src = src0->view_src ? src0->view_src : src0;
  6355. dst2.view_offs += m_offset * dst->nb[0];
  6356. src02.view_offs += m_offset * src0->nb[1];
  6357. dst2.ne[0] = cur_M_size;
  6358. src02.ne[1] = cur_M_size;
  6359. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6360. m_offset += cur_M_size;
  6361. }
  6362. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6363. // detect 0213 permutation, and batch size of 1
  6364. src0->nb[0] <= src0->nb[2] &&
  6365. src0->nb[2] <= src0->nb[1] &&
  6366. src0->nb[1] <= src0->nb[3] &&
  6367. src1->nb[0] <= src1->nb[2] &&
  6368. src1->nb[2] <= src1->nb[1] &&
  6369. src1->nb[1] <= src1->nb[3] &&
  6370. src0->ne[3] == 1 &&
  6371. src1->ne[3] == 1) {
  6372. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6373. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6374. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6375. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6376. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6377. // when ne12 and ne13 are one.
  6378. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6379. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6380. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6381. } else {
  6382. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6383. }
  6384. }
  6385. 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) {
  6386. 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];
  6387. 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];
  6388. 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];
  6389. 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] << "),)");
  6390. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6391. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6392. const uint64_t ne00 = src0->ne[0];
  6393. const uint64_t ne01 = src0->ne[1];
  6394. const uint64_t ne02 = src0->ne[2];
  6395. // const uint64_t ne03 = src0->ne[3];
  6396. const uint64_t ne10 = src1->ne[0];
  6397. const uint64_t ne11 = src1->ne[1];
  6398. const uint64_t ne12 = src1->ne[2];
  6399. const uint64_t ne13 = src1->ne[3];
  6400. const uint64_t nei0 = ids->ne[0];
  6401. const uint64_t nei1 = ids->ne[1];
  6402. const uint32_t nbi1 = ids->nb[1];
  6403. const uint32_t nbi2 = ids->nb[2];
  6404. const uint64_t ne20 = dst->ne[0];
  6405. const uint64_t ne21 = dst->ne[1];
  6406. // const uint64_t ne22 = dst->ne[2];
  6407. // const uint64_t ne23 = dst->ne[3];
  6408. const uint64_t n_as = ne02;
  6409. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6410. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6411. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6412. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6413. vk_buffer d_Qx = nullptr;
  6414. size_t qx_buf_offset = 0;
  6415. vk_buffer d_Qy = nullptr;
  6416. size_t qy_buf_offset = 0;
  6417. vk_buffer d_ids = nullptr;
  6418. size_t ids_buf_offset = 0;
  6419. bool src0_uma = false;
  6420. bool src1_uma = false;
  6421. bool ids_uma = false;
  6422. if (ctx->device->uma) {
  6423. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6424. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6425. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6426. src0_uma = d_Qx != nullptr;
  6427. src1_uma = d_Qy != nullptr;
  6428. ids_uma = d_ids != nullptr;
  6429. }
  6430. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6431. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6432. !ggml_vk_dim01_contiguous(src0);
  6433. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6434. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6435. !ggml_vk_dim01_contiguous(src1);
  6436. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6437. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6438. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6439. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6440. // Check for mmq first
  6441. vk_matmul_pipeline mmp = quantize_y ? ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, GGML_TYPE_Q8_1, (ggml_prec)dst->op_params[0]) : nullptr;
  6442. if (mmp == nullptr) {
  6443. // Fall back to f16 dequant mul mat
  6444. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  6445. quantize_y = false;
  6446. }
  6447. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6448. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6449. if (qx_needs_dequant) {
  6450. // Fall back to dequant + f16 mulmat
  6451. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, f16_type, y_f32_kernel ? GGML_TYPE_F32 : f16_type, (ggml_prec)dst->op_params[0]);
  6452. }
  6453. // Not implemented
  6454. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6455. const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1, qx_needs_dequant ? f16_type : src0->type));
  6456. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6457. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6458. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6459. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6460. const uint64_t x_ne = ggml_nelements(src0);
  6461. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6462. const uint64_t d_ne = ggml_nelements(dst);
  6463. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6464. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6465. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6466. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6467. const uint64_t ids_sz = nbi2;
  6468. const uint64_t d_sz = sizeof(float) * d_ne;
  6469. vk_pipeline to_fp16_vk_0 = nullptr;
  6470. vk_pipeline to_fp16_vk_1 = nullptr;
  6471. vk_pipeline to_q8_1 = nullptr;
  6472. if (x_non_contig) {
  6473. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6474. } else {
  6475. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6476. }
  6477. if (y_non_contig) {
  6478. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6479. } else {
  6480. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6481. }
  6482. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6483. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6484. if (quantize_y) {
  6485. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6486. }
  6487. {
  6488. if (
  6489. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6490. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6491. GGML_ABORT("Requested preallocation size is too large");
  6492. }
  6493. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6494. ctx->prealloc_size_x = x_sz;
  6495. ggml_vk_preallocate_buffers(ctx, subctx);
  6496. }
  6497. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6498. ctx->prealloc_size_y = y_sz;
  6499. ggml_vk_preallocate_buffers(ctx, subctx);
  6500. }
  6501. // Request descriptor sets
  6502. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6503. if (qx_needs_dequant) {
  6504. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6505. }
  6506. if (qy_needs_dequant) {
  6507. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6508. }
  6509. if (quantize_y) {
  6510. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6511. }
  6512. }
  6513. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6514. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6515. GGML_ASSERT(d_D != nullptr);
  6516. vk_buffer d_X;
  6517. uint64_t x_buf_offset = 0;
  6518. vk_buffer d_Y;
  6519. uint64_t y_buf_offset = 0;
  6520. if (!src0_uma) {
  6521. d_Qx = src0_buf_ctx->dev_buffer;
  6522. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6523. GGML_ASSERT(d_Qx != nullptr);
  6524. }
  6525. if (!src1_uma) {
  6526. d_Qy = src1_buf_ctx->dev_buffer;
  6527. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6528. GGML_ASSERT(d_Qy != nullptr);
  6529. }
  6530. if (!ids_uma) {
  6531. d_ids = ids_buf_ctx->dev_buffer;
  6532. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6533. GGML_ASSERT(d_ids != nullptr);
  6534. }
  6535. if (qx_needs_dequant) {
  6536. d_X = ctx->prealloc_x;
  6537. GGML_ASSERT(d_X->size >= x_sz);
  6538. } else {
  6539. d_X = d_Qx;
  6540. x_buf_offset = qx_buf_offset;
  6541. GGML_ASSERT(qx_sz == x_sz);
  6542. }
  6543. if (qy_needs_dequant) {
  6544. d_Y = ctx->prealloc_y;
  6545. GGML_ASSERT(d_Y->size >= y_sz);
  6546. } else if (quantize_y) {
  6547. d_Y = ctx->prealloc_y;
  6548. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6549. } else {
  6550. d_Y = d_Qy;
  6551. y_buf_offset = qy_buf_offset;
  6552. GGML_ASSERT(qy_sz == y_sz);
  6553. }
  6554. if (x_non_contig || qx_needs_dequant) {
  6555. if (ctx->prealloc_x_need_sync) {
  6556. ggml_vk_sync_buffers(ctx, subctx);
  6557. }
  6558. }
  6559. if (x_non_contig) {
  6560. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  6561. } else if (qx_needs_dequant) {
  6562. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6563. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6564. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6565. ggml_vk_sync_buffers(ctx, subctx);
  6566. }
  6567. if (y_non_contig) {
  6568. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6569. ctx->prealloc_y_last_tensor_used != src1) {
  6570. if (ctx->prealloc_y_need_sync) {
  6571. ggml_vk_sync_buffers(ctx, subctx);
  6572. }
  6573. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  6574. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6575. ctx->prealloc_y_last_tensor_used = src1;
  6576. }
  6577. }
  6578. if (quantize_y) {
  6579. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6580. ctx->prealloc_y_last_tensor_used != src1) {
  6581. if (ctx->prealloc_y_need_sync) {
  6582. ggml_vk_sync_buffers(ctx, subctx);
  6583. }
  6584. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne);
  6585. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6586. ctx->prealloc_y_last_tensor_used = src1;
  6587. }
  6588. }
  6589. uint32_t stride_batch_x = ne00*ne01;
  6590. uint32_t stride_batch_y = ne10*ne11;
  6591. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6592. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6593. }
  6594. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6595. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6596. }
  6597. // compute
  6598. ggml_vk_matmul_id(
  6599. ctx, subctx, pipeline,
  6600. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6601. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz },
  6602. ne01, ne21, ne10, ne10, ne10, ne01,
  6603. stride_batch_x, stride_batch_y, ne20*ne21,
  6604. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6605. ); // NOLINT
  6606. if (x_non_contig || qx_needs_dequant) {
  6607. ctx->prealloc_x_need_sync = true;
  6608. }
  6609. if (y_non_contig || quantize_y) {
  6610. ctx->prealloc_y_need_sync = true;
  6611. }
  6612. }
  6613. static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6614. ggml_tensor * dst = cgraph->nodes[node_idx];
  6615. ggml_tensor * src0 = dst->src[0];
  6616. ggml_tensor * src1 = dst->src[1];
  6617. ggml_tensor * ids = dst->src[2];
  6618. 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];
  6619. 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];
  6620. 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];
  6621. 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];
  6622. std::cerr << "))");
  6623. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6624. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6625. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6626. const uint64_t ne00 = src0->ne[0];
  6627. const uint64_t ne01 = src0->ne[1];
  6628. // const uint64_t ne02 = src0->ne[2];
  6629. // const uint64_t ne03 = src0->ne[3];
  6630. const uint64_t ne10 = src1->ne[0];
  6631. const uint64_t ne11 = src1->ne[1];
  6632. const uint64_t ne12 = src1->ne[2];
  6633. // const uint64_t ne13 = src1->ne[3];
  6634. const uint64_t nei0 = ids->ne[0];
  6635. const uint64_t nei1 = ids->ne[1];
  6636. GGML_ASSERT(nei1 == 1);
  6637. const uint64_t ne20 = dst->ne[0];
  6638. const uint64_t ne21 = dst->ne[1];
  6639. // const uint64_t ne22 = dst->ne[2];
  6640. // const uint64_t ne23 = dst->ne[3];
  6641. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6642. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6643. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6644. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne12, ne10, src0->type);
  6645. vk_pipeline to_fp16_vk_0 = nullptr;
  6646. vk_pipeline to_fp16_vk_1 = nullptr;
  6647. if (x_non_contig) {
  6648. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6649. }
  6650. if (y_non_contig) {
  6651. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6652. } else {
  6653. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6654. }
  6655. // Check for mmq first
  6656. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00) : nullptr;
  6657. vk_pipeline to_q8_1 = nullptr;
  6658. if (dmmv == nullptr) {
  6659. // Fall back to f16 dequant mul mat
  6660. dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00);
  6661. quantize_y = false;
  6662. }
  6663. if (quantize_y) {
  6664. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6665. }
  6666. const bool qx_needs_dequant = x_non_contig;
  6667. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6668. // Not implemented
  6669. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6670. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6671. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6672. GGML_ASSERT(dmmv != nullptr);
  6673. const uint64_t x_ne = ggml_nelements(src0);
  6674. const uint64_t y_ne = ggml_nelements(src1);
  6675. 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);
  6676. 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;
  6677. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) :
  6678. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6679. {
  6680. if (
  6681. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6682. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6683. GGML_ABORT("Requested preallocation size is too large");
  6684. }
  6685. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6686. ctx->prealloc_size_x = x_sz;
  6687. ggml_vk_preallocate_buffers(ctx, subctx);
  6688. }
  6689. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6690. ctx->prealloc_size_y = y_sz;
  6691. ggml_vk_preallocate_buffers(ctx, subctx);
  6692. }
  6693. // Request descriptor sets
  6694. if (qx_needs_dequant) {
  6695. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6696. }
  6697. if (qy_needs_dequant) {
  6698. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6699. }
  6700. if (quantize_y) {
  6701. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6702. }
  6703. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6704. }
  6705. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6706. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6707. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6708. vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids);
  6709. vk_subbuffer d_F0 = d_D;
  6710. vk_subbuffer d_X, d_Y;
  6711. if (qx_needs_dequant) {
  6712. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6713. } else {
  6714. d_X = d_Qx;
  6715. }
  6716. if (qy_needs_dequant || quantize_y) {
  6717. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6718. } else {
  6719. d_Y = d_Qy;
  6720. }
  6721. if (x_non_contig) {
  6722. if (ctx->prealloc_x_need_sync) {
  6723. ggml_vk_sync_buffers(ctx, subctx);
  6724. }
  6725. }
  6726. if (x_non_contig) {
  6727. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6728. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6729. }
  6730. if (y_non_contig) {
  6731. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6732. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6733. ctx->prealloc_y_last_tensor_used != src1) {
  6734. if (ctx->prealloc_y_need_sync) {
  6735. ggml_vk_sync_buffers(ctx, subctx);
  6736. }
  6737. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6738. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6739. ctx->prealloc_y_last_tensor_used = src1;
  6740. }
  6741. }
  6742. if (quantize_y) {
  6743. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6744. ctx->prealloc_y_last_tensor_used != src1) {
  6745. if (ctx->prealloc_y_need_sync) {
  6746. ggml_vk_sync_buffers(ctx, subctx);
  6747. }
  6748. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6749. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6750. ctx->prealloc_y_last_tensor_used = src1;
  6751. }
  6752. }
  6753. uint32_t stride_batch_y = ne10*ne11;
  6754. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6755. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6756. }
  6757. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6758. uint32_t groups_x = ne01;
  6759. uint32_t groups_z = 1;
  6760. if (ne01 > max_groups_x) {
  6761. groups_z = 64;
  6762. groups_x = CEIL_DIV(groups_x, groups_z);
  6763. }
  6764. uint32_t fusion_flags = 0;
  6765. if (ctx->num_additional_fused_ops > 0) {
  6766. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6767. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6768. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  6769. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0;
  6770. } else {
  6771. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  6772. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6773. }
  6774. }
  6775. vk_subbuffer d_F1 = d_D;
  6776. if (ctx->num_additional_fused_ops > 1) {
  6777. const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1];
  6778. d_F1 = ggml_vk_tensor_subbuffer(ctx, scale);
  6779. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
  6780. }
  6781. // compute
  6782. const vk_mat_vec_id_push_constants pc = {
  6783. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6784. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  6785. fusion_flags,
  6786. (uint32_t)nei0, (uint32_t)ne11,
  6787. };
  6788. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6789. {
  6790. d_X,
  6791. d_Y,
  6792. d_D,
  6793. d_F0,
  6794. d_F1,
  6795. d_ids,
  6796. },
  6797. pc, { groups_x, (uint32_t)nei0, groups_z });
  6798. if (x_non_contig) {
  6799. ctx->prealloc_x_need_sync = true;
  6800. }
  6801. if (y_non_contig || quantize_y) {
  6802. ctx->prealloc_y_need_sync = true;
  6803. }
  6804. }
  6805. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  6806. ggml_tensor * dst = cgraph->nodes[node_idx];
  6807. ggml_tensor * src0 = dst->src[0];
  6808. ggml_tensor * src2 = dst->src[2];
  6809. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  6810. }
  6811. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6812. ggml_tensor * dst = cgraph->nodes[node_idx];
  6813. ggml_tensor * src0 = dst->src[0];
  6814. ggml_tensor * src1 = dst->src[1];
  6815. ggml_tensor * src2 = dst->src[2];
  6816. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6817. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  6818. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  6819. } else {
  6820. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  6821. }
  6822. }
  6823. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6824. // Needs to be kept up to date on shader changes
  6825. GGML_UNUSED(hsv);
  6826. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6827. const uint32_t Br = get_fa_scalar_num_large_rows(hsk, hsv);
  6828. const uint32_t Bc = scalar_flash_attention_Bc;
  6829. const uint32_t tmpsh = wg_size * sizeof(float);
  6830. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6831. const uint32_t masksh = Bc * Br * sizeof(float);
  6832. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6833. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6834. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6835. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6836. return supported;
  6837. }
  6838. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6839. // Needs to be kept up to date on shader changes
  6840. GGML_UNUSED(hsv);
  6841. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6842. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6843. const uint32_t Bc = scalar_flash_attention_Bc;
  6844. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6845. const uint32_t acctype = f32acc ? 4 : 2;
  6846. const uint32_t f16vec4 = 8;
  6847. const uint32_t tmpsh = wg_size * sizeof(float);
  6848. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6849. const uint32_t qstride = hsk_pad / 4 + 2;
  6850. const uint32_t Qf = Br * qstride * f16vec4;
  6851. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6852. const uint32_t sfsh = Bc * sfshstride * acctype;
  6853. const uint32_t kshstride = hsk_pad / 4 + 2;
  6854. const uint32_t ksh = Bc * kshstride * f16vec4;
  6855. const uint32_t slope = Br * sizeof(float);
  6856. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6857. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6858. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6859. return supported;
  6860. }
  6861. static void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v, const ggml_tensor * mask, const ggml_tensor * sinks, ggml_tensor * dst) {
  6862. 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];
  6863. 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];
  6864. 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];
  6865. 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];
  6866. if (sinks) {
  6867. std::cerr << "), (" << sinks << ", name=" << sinks->name << ", type=" << sinks->type << ", ne0=" << sinks->ne[0] << ", ne1=" << sinks->ne[1] << ", ne2=" << sinks->ne[2] << ", ne3=" << sinks->ne[3] << ", nb0=" << sinks->nb[0] << ", nb1=" << sinks->nb[1] << ", nb2=" << sinks->nb[2] << ", nb3=" << sinks->nb[3];
  6868. }
  6869. std::cerr << "))");
  6870. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6871. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6872. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6873. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6874. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6875. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6876. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6877. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6878. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6879. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6880. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6881. const uint32_t HSK = nek0;
  6882. const uint32_t HSV = nev0;
  6883. uint32_t N = neq1;
  6884. const uint32_t KV = nek1;
  6885. GGML_ASSERT(ne0 == HSV);
  6886. GGML_ASSERT(ne2 == N);
  6887. // input tensor rows must be contiguous
  6888. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6889. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6890. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6891. GGML_ASSERT(neq0 == HSK);
  6892. GGML_ASSERT(neq1 == N);
  6893. GGML_ASSERT(nev1 == nek1);
  6894. // dst cannot be transposed or permuted
  6895. GGML_ASSERT(nb0 == sizeof(float));
  6896. GGML_ASSERT(nb0 <= nb1);
  6897. GGML_ASSERT(nb1 <= nb2);
  6898. GGML_ASSERT(nb2 <= nb3);
  6899. assert(dst->type == GGML_TYPE_F32);
  6900. assert(q->type == GGML_TYPE_F32);
  6901. assert(k->type == v->type);
  6902. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6903. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6904. if (path == FA_COOPMAT1) {
  6905. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6906. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6907. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6908. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6909. path = FA_SCALAR;
  6910. }
  6911. }
  6912. uint32_t gqa_ratio = 1;
  6913. uint32_t qk_ratio = neq2 / nek2;
  6914. uint32_t workgroups_x = (uint32_t)neq1;
  6915. uint32_t workgroups_y = (uint32_t)neq2;
  6916. uint32_t workgroups_z = (uint32_t)neq3;
  6917. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6918. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6919. uint32_t max_gqa;
  6920. switch (path) {
  6921. case FA_SCALAR:
  6922. case FA_COOPMAT1:
  6923. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6924. max_gqa = get_fa_scalar_num_large_rows(HSK, HSV);
  6925. break;
  6926. case FA_COOPMAT2:
  6927. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6928. break;
  6929. default:
  6930. GGML_ASSERT(0);
  6931. }
  6932. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6933. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6934. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6935. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6936. // and change addressing calculations to index Q's dimension 2.
  6937. gqa_ratio = qk_ratio;
  6938. N = gqa_ratio;
  6939. workgroups_y /= N;
  6940. }
  6941. bool small_rows = N <= get_fa_num_small_rows(path);
  6942. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6943. // So use scalar instead.
  6944. if (small_rows && path == FA_COOPMAT1) {
  6945. path = FA_SCALAR;
  6946. }
  6947. // scalar is faster than coopmat2 when N==1
  6948. if (N == 1 && path == FA_COOPMAT2) {
  6949. path = FA_SCALAR;
  6950. }
  6951. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6952. if (path == FA_SCALAR &&
  6953. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6954. small_rows = true;
  6955. }
  6956. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6957. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6958. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6959. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  6960. if (k->type == GGML_TYPE_F32) {
  6961. k_stride /= 4;
  6962. }
  6963. if (v->type == GGML_TYPE_F32) {
  6964. v_stride /= 4;
  6965. }
  6966. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6967. bool aligned = (KV % alignment) == 0 &&
  6968. // the "aligned" shader variant will forcibly align strides, for performance
  6969. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6970. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6971. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6972. aligned = false;
  6973. }
  6974. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6975. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6976. vk_pipeline pipeline = nullptr;
  6977. {
  6978. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  6979. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6980. auto it = pipelines.find(fa_pipeline_state);
  6981. if (it != pipelines.end()) {
  6982. pipeline = it->second;
  6983. } else {
  6984. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6985. }
  6986. }
  6987. assert(pipeline);
  6988. uint32_t split_kv = KV;
  6989. uint32_t split_k = 1;
  6990. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6991. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6992. // Try to use split_k when KV is large enough to be worth the overhead
  6993. if (workgroups_x == 1 && shader_core_count > 0) {
  6994. // Try to run two workgroups per SM.
  6995. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6996. if (split_k > 1) {
  6997. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6998. // of "align", so recompute split_k based on that.
  6999. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  7000. split_k = CEIL_DIV(KV, split_kv);
  7001. workgroups_x = split_k;
  7002. }
  7003. }
  7004. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  7005. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  7006. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  7007. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  7008. GGML_ABORT("Requested preallocation size is too large");
  7009. }
  7010. if (ctx->prealloc_size_split_k < split_k_size) {
  7011. ctx->prealloc_size_split_k = split_k_size;
  7012. ggml_vk_preallocate_buffers(ctx, subctx);
  7013. }
  7014. {
  7015. // Request descriptor sets
  7016. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7017. if (split_k > 1) {
  7018. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  7019. }
  7020. }
  7021. float scale = 1.0f;
  7022. float max_bias = 0.0f;
  7023. float logit_softcap = 0.0f;
  7024. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  7025. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  7026. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  7027. if (logit_softcap != 0) {
  7028. scale /= logit_softcap;
  7029. }
  7030. const uint32_t n_head_kv = neq2;
  7031. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  7032. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  7033. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  7034. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  7035. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  7036. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  7037. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  7038. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  7039. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  7040. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  7041. const vk_flash_attn_push_constants pc = { N, KV,
  7042. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  7043. (uint32_t)neq2, (uint32_t)neq3,
  7044. (uint32_t)nek2, (uint32_t)nek3,
  7045. (uint32_t)nev2, (uint32_t)nev3,
  7046. nem1, nem2, nem3,
  7047. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  7048. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  7049. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  7050. scale, max_bias, logit_softcap,
  7051. mask_n_head_log2, m0, m1,
  7052. gqa_ratio, split_kv, split_k };
  7053. if (split_k > 1) {
  7054. if (ctx->prealloc_split_k_need_sync) {
  7055. ggml_vk_sync_buffers(ctx, subctx);
  7056. }
  7057. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  7058. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7059. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  7060. // We only use split_k when group query attention is enabled, which means
  7061. // there's no more than one tile of rows (i.e. workgroups_x would have been
  7062. // one). We reuse workgroups_x to mean the number of splits, so we need to
  7063. // cancel out the divide by wg_denoms[0].
  7064. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  7065. ggml_vk_sync_buffers(ctx, subctx);
  7066. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  7067. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  7068. {split_k_buf, sinks_buf, dst_buf},
  7069. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  7070. ctx->prealloc_split_k_need_sync = true;
  7071. } else {
  7072. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7073. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  7074. pc, { workgroups_x, workgroups_y, workgroups_z });
  7075. }
  7076. }
  7077. static vk_conv_shapes ggml_vk_conv_select_shape(ggml_backend_vk_context * ctx, uint32_t K, uint32_t NPQ) {
  7078. auto n_tiles = [&](vk_conv_shapes s) {
  7079. return CEIL_DIV(K, vk_conv_block_sizes[s].K)
  7080. * CEIL_DIV(NPQ, vk_conv_block_sizes[s].NPQ);
  7081. };
  7082. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7083. // so small convolutions will still choose a smaller tile.
  7084. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7085. if (K > 64 && n_tiles(CONV_SHAPE_128x128) >= shader_core_count * 2) {
  7086. return CONV_SHAPE_128x128;
  7087. } else if (K <= 32 && n_tiles(CONV_SHAPE_32x256) >= shader_core_count * 2) {
  7088. return CONV_SHAPE_32x256;
  7089. } else {
  7090. return CONV_SHAPE_64x32;
  7091. }
  7092. }
  7093. static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * dst, ggml_op op) {
  7094. switch (op) {
  7095. case GGML_OP_GET_ROWS:
  7096. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  7097. if (src0->type == GGML_TYPE_I32) {
  7098. // i32 src only supports i32 result
  7099. GGML_ASSERT(dst->type == GGML_TYPE_I32);
  7100. return ctx->device->pipeline_get_rows[src0->type];
  7101. }
  7102. if (dst->type == GGML_TYPE_F16) {
  7103. return ctx->device->pipeline_get_rows[src0->type];
  7104. }
  7105. if (dst->type == GGML_TYPE_F32) {
  7106. return ctx->device->pipeline_get_rows_f32[src0->type];
  7107. }
  7108. return nullptr;
  7109. case GGML_OP_ACC:
  7110. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7111. return ctx->device->pipeline_acc_f32;
  7112. }
  7113. return nullptr;
  7114. case GGML_OP_ADD:
  7115. case GGML_OP_SUB:
  7116. case GGML_OP_MUL:
  7117. case GGML_OP_DIV:
  7118. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7119. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  7120. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  7121. return nullptr;
  7122. }
  7123. switch (op) {
  7124. case GGML_OP_ADD:
  7125. {
  7126. if (ctx->num_additional_fused_ops > 0) {
  7127. if (ctx->do_add_rms_partials) {
  7128. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  7129. } else {
  7130. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  7131. }
  7132. }
  7133. if (ctx->do_add_rms_partials) {
  7134. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  7135. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7136. } else {
  7137. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  7138. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7139. }
  7140. }
  7141. case GGML_OP_SUB:
  7142. {
  7143. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  7144. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7145. }
  7146. case GGML_OP_MUL:
  7147. {
  7148. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  7149. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7150. }
  7151. case GGML_OP_DIV:
  7152. {
  7153. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  7154. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7155. }
  7156. default:
  7157. break;
  7158. }
  7159. return nullptr;
  7160. case GGML_OP_ADD_ID:
  7161. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7162. return ctx->device->pipeline_add_id_f32;
  7163. }
  7164. return nullptr;
  7165. case GGML_OP_CONCAT:
  7166. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7167. return ctx->device->pipeline_concat_f32;
  7168. }
  7169. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7170. return ctx->device->pipeline_concat_f16;
  7171. }
  7172. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7173. return ctx->device->pipeline_concat_i32;
  7174. }
  7175. return nullptr;
  7176. case GGML_OP_UPSCALE:
  7177. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7178. ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(dst, 0) & 0xFF);
  7179. switch (mode) {
  7180. case GGML_SCALE_MODE_NEAREST:
  7181. return ctx->device->pipeline_upscale_nearest_f32;
  7182. case GGML_SCALE_MODE_BILINEAR:
  7183. return ctx->device->pipeline_upscale_bilinear_f32;
  7184. case GGML_SCALE_MODE_BICUBIC:
  7185. return ctx->device->pipeline_upscale_bicubic_f32;
  7186. default:
  7187. return nullptr;
  7188. }
  7189. }
  7190. return nullptr;
  7191. case GGML_OP_SCALE:
  7192. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7193. return ctx->device->pipeline_scale_f32;
  7194. }
  7195. return nullptr;
  7196. case GGML_OP_SQR:
  7197. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7198. return ctx->device->pipeline_sqr_f32;
  7199. }
  7200. return nullptr;
  7201. case GGML_OP_SQRT:
  7202. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7203. return ctx->device->pipeline_sqrt_f32;
  7204. }
  7205. return nullptr;
  7206. case GGML_OP_SIN:
  7207. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7208. return ctx->device->pipeline_sin_f32;
  7209. }
  7210. return nullptr;
  7211. case GGML_OP_COS:
  7212. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7213. return ctx->device->pipeline_cos_f32;
  7214. }
  7215. return nullptr;
  7216. case GGML_OP_LOG:
  7217. if (src0->type == dst->type &&
  7218. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7219. return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16];
  7220. }
  7221. return nullptr;
  7222. case GGML_OP_TRI:
  7223. if (src0->type == dst->type &&
  7224. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7225. return ctx->device->pipeline_tri[dst->type == GGML_TYPE_F16];
  7226. }
  7227. return nullptr;
  7228. case GGML_OP_DIAG:
  7229. if (src0->type == dst->type &&
  7230. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7231. return ctx->device->pipeline_diag[dst->type == GGML_TYPE_F16];
  7232. }
  7233. return nullptr;
  7234. case GGML_OP_CLAMP:
  7235. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7236. return ctx->device->pipeline_clamp_f32;
  7237. }
  7238. return nullptr;
  7239. case GGML_OP_PAD:
  7240. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7241. return ctx->device->pipeline_pad_f32;
  7242. }
  7243. return nullptr;
  7244. case GGML_OP_ROLL:
  7245. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7246. return ctx->device->pipeline_roll_f32;
  7247. }
  7248. return nullptr;
  7249. case GGML_OP_REPEAT:
  7250. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7251. return ctx->device->pipeline_repeat_f32;
  7252. }
  7253. return nullptr;
  7254. case GGML_OP_REPEAT_BACK:
  7255. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7256. return ctx->device->pipeline_repeat_back_f32;
  7257. }
  7258. return nullptr;
  7259. case GGML_OP_CPY:
  7260. case GGML_OP_CONT:
  7261. case GGML_OP_DUP:
  7262. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7263. case GGML_OP_SET_ROWS:
  7264. if (src1->type == GGML_TYPE_I64) {
  7265. return ctx->device->pipeline_set_rows_i64[dst->type];
  7266. } else {
  7267. return ctx->device->pipeline_set_rows_i32[dst->type];
  7268. }
  7269. case GGML_OP_SILU_BACK:
  7270. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7271. return ctx->device->pipeline_silu_back_f32;
  7272. }
  7273. return nullptr;
  7274. case GGML_OP_NORM:
  7275. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7276. return ctx->device->pipeline_norm_f32;
  7277. }
  7278. return nullptr;
  7279. case GGML_OP_GROUP_NORM:
  7280. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7281. return ctx->device->pipeline_group_norm_f32;
  7282. }
  7283. return nullptr;
  7284. case GGML_OP_RMS_NORM:
  7285. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7286. if (ctx->do_add_rms_partials) {
  7287. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7288. } else {
  7289. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7290. }
  7291. }
  7292. return nullptr;
  7293. case GGML_OP_RMS_NORM_BACK:
  7294. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7295. return ctx->device->pipeline_rms_norm_back_f32;
  7296. }
  7297. return nullptr;
  7298. case GGML_OP_L2_NORM:
  7299. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7300. return ctx->device->pipeline_l2_norm_f32;
  7301. }
  7302. return nullptr;
  7303. case GGML_OP_UNARY:
  7304. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7305. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7306. (src0->type != dst->type)) {
  7307. return nullptr;
  7308. }
  7309. switch (ggml_get_unary_op(dst)) {
  7310. case GGML_UNARY_OP_EXP:
  7311. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7312. case GGML_UNARY_OP_SILU:
  7313. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7314. case GGML_UNARY_OP_GELU:
  7315. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7316. case GGML_UNARY_OP_GELU_ERF:
  7317. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7318. case GGML_UNARY_OP_GELU_QUICK:
  7319. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7320. case GGML_UNARY_OP_RELU:
  7321. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7322. case GGML_UNARY_OP_NEG:
  7323. return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16];
  7324. case GGML_UNARY_OP_TANH:
  7325. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7326. case GGML_UNARY_OP_SIGMOID:
  7327. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7328. case GGML_UNARY_OP_HARDSIGMOID:
  7329. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7330. case GGML_UNARY_OP_HARDSWISH:
  7331. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7332. case GGML_UNARY_OP_ABS:
  7333. return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16];
  7334. case GGML_UNARY_OP_SOFTPLUS:
  7335. return ctx->device->pipeline_softplus[dst->type == GGML_TYPE_F16];
  7336. case GGML_UNARY_OP_STEP:
  7337. return ctx->device->pipeline_step[dst->type == GGML_TYPE_F16];
  7338. case GGML_UNARY_OP_ROUND:
  7339. return ctx->device->pipeline_round[dst->type == GGML_TYPE_F16];
  7340. case GGML_UNARY_OP_CEIL:
  7341. return ctx->device->pipeline_ceil[dst->type == GGML_TYPE_F16];
  7342. case GGML_UNARY_OP_FLOOR:
  7343. return ctx->device->pipeline_floor[dst->type == GGML_TYPE_F16];
  7344. case GGML_UNARY_OP_TRUNC:
  7345. return ctx->device->pipeline_trunc[dst->type == GGML_TYPE_F16];
  7346. default:
  7347. break;
  7348. }
  7349. return nullptr;
  7350. case GGML_OP_GLU:
  7351. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7352. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7353. (src0->type != dst->type)) {
  7354. return nullptr;
  7355. }
  7356. switch (ggml_get_glu_op(dst)) {
  7357. case GGML_GLU_OP_GEGLU:
  7358. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7359. case GGML_GLU_OP_REGLU:
  7360. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7361. case GGML_GLU_OP_SWIGLU:
  7362. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7363. case GGML_GLU_OP_SWIGLU_OAI:
  7364. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7365. case GGML_GLU_OP_GEGLU_ERF:
  7366. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7367. case GGML_GLU_OP_GEGLU_QUICK:
  7368. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7369. default:
  7370. break;
  7371. }
  7372. return nullptr;
  7373. case GGML_OP_DIAG_MASK_INF:
  7374. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7375. return ctx->device->pipeline_diag_mask_inf_f32;
  7376. }
  7377. return nullptr;
  7378. case GGML_OP_SOFT_MAX:
  7379. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7380. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7381. if (ctx->num_additional_fused_ops) {
  7382. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7383. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7384. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7385. // use n_experts from push constant if it's not equal to the power of two spec constant
  7386. bool use_push = dst->ne[0] != (1u << idx);
  7387. return ctx->device->pipeline_topk_moe[idx][mode][use_push];
  7388. }
  7389. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7390. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7391. }
  7392. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7393. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7394. }
  7395. return nullptr;
  7396. case GGML_OP_SOFT_MAX_BACK:
  7397. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7398. return ctx->device->pipeline_soft_max_back_f32;
  7399. }
  7400. return nullptr;
  7401. case GGML_OP_ROPE:
  7402. case GGML_OP_ROPE_BACK:
  7403. {
  7404. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7405. const int mode = ((const int32_t *) rope->op_params)[2];
  7406. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7407. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7408. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7409. if (is_neox) {
  7410. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7411. return ctx->device->pipeline_rope_neox_f32;
  7412. }
  7413. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7414. return ctx->device->pipeline_rope_neox_f32_f16;
  7415. }
  7416. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7417. return ctx->device->pipeline_rope_neox_f16;
  7418. }
  7419. } else if (is_mrope && !is_vision) {
  7420. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7421. return ctx->device->pipeline_rope_multi_f32;
  7422. }
  7423. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7424. return ctx->device->pipeline_rope_multi_f16;
  7425. }
  7426. } else if (is_vision) {
  7427. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7428. return ctx->device->pipeline_rope_vision_f32;
  7429. }
  7430. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7431. return ctx->device->pipeline_rope_vision_f16;
  7432. }
  7433. } else {
  7434. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7435. return ctx->device->pipeline_rope_norm_f32;
  7436. }
  7437. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7438. return ctx->device->pipeline_rope_norm_f32_f16;
  7439. }
  7440. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7441. return ctx->device->pipeline_rope_norm_f16;
  7442. }
  7443. }
  7444. return nullptr;
  7445. }
  7446. case GGML_OP_SUM:
  7447. case GGML_OP_SUM_ROWS:
  7448. case GGML_OP_MEAN:
  7449. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7450. return ctx->device->pipeline_sum_rows_f32;
  7451. }
  7452. return nullptr;
  7453. case GGML_OP_CUMSUM:
  7454. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7455. return ctx->device->pipeline_cumsum_f32;
  7456. }
  7457. return nullptr;
  7458. case GGML_OP_SOLVE_TRI:
  7459. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7460. vk_solve_tri_pipeline_state solve_tri_pipeline_state(src0->ne[0], src1->ne[0]);
  7461. vk_pipeline pipeline = nullptr;
  7462. {
  7463. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7464. auto it = ctx->device->pipeline_solve_tri_f32.find(solve_tri_pipeline_state);
  7465. if (it != ctx->device->pipeline_solve_tri_f32.end()) {
  7466. pipeline = it->second;
  7467. } else {
  7468. ctx->device->pipeline_solve_tri_f32[solve_tri_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7469. }
  7470. }
  7471. return pipeline;
  7472. }
  7473. return nullptr;
  7474. case GGML_OP_ARGMAX:
  7475. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7476. return ctx->device->pipeline_argmax_f32;
  7477. }
  7478. return nullptr;
  7479. case GGML_OP_COUNT_EQUAL:
  7480. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7481. return ctx->device->pipeline_count_equal_i32;
  7482. }
  7483. return nullptr;
  7484. case GGML_OP_IM2COL:
  7485. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7486. return ctx->device->pipeline_im2col_f32;
  7487. }
  7488. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7489. return ctx->device->pipeline_im2col_f32_f16;
  7490. }
  7491. return nullptr;
  7492. case GGML_OP_IM2COL_3D:
  7493. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7494. return ctx->device->pipeline_im2col_3d_f32;
  7495. }
  7496. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7497. return ctx->device->pipeline_im2col_3d_f32_f16;
  7498. }
  7499. return nullptr;
  7500. case GGML_OP_TIMESTEP_EMBEDDING:
  7501. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7502. return ctx->device->pipeline_timestep_embedding_f32;
  7503. }
  7504. return nullptr;
  7505. case GGML_OP_CONV_TRANSPOSE_1D:
  7506. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7507. return ctx->device->pipeline_conv_transpose_1d_f32;
  7508. }
  7509. return nullptr;
  7510. case GGML_OP_POOL_2D:
  7511. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7512. return ctx->device->pipeline_pool2d_f32;
  7513. }
  7514. return nullptr;
  7515. case GGML_OP_RWKV_WKV6:
  7516. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7517. return ctx->device->pipeline_rwkv_wkv6_f32;
  7518. }
  7519. return nullptr;
  7520. case GGML_OP_RWKV_WKV7:
  7521. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7522. return ctx->device->pipeline_rwkv_wkv7_f32;
  7523. }
  7524. return nullptr;
  7525. case GGML_OP_SSM_SCAN:
  7526. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7527. const uint32_t d_state = src0->ne[0];
  7528. if (d_state == 128) {
  7529. return ctx->device->pipeline_ssm_scan_f32_d128;
  7530. } else if (d_state == 256) {
  7531. return ctx->device->pipeline_ssm_scan_f32_d256;
  7532. }
  7533. }
  7534. return nullptr;
  7535. case GGML_OP_SSM_CONV:
  7536. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7537. return ctx->device->pipeline_ssm_conv_f32;
  7538. }
  7539. return nullptr;
  7540. case GGML_OP_OPT_STEP_ADAMW:
  7541. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7542. return ctx->device->pipeline_opt_step_adamw_f32;
  7543. }
  7544. return nullptr;
  7545. case GGML_OP_OPT_STEP_SGD:
  7546. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7547. return ctx->device->pipeline_opt_step_sgd_f32;
  7548. }
  7549. return nullptr;
  7550. case GGML_OP_LEAKY_RELU:
  7551. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7552. return ctx->device->pipeline_leaky_relu_f32;
  7553. }
  7554. return nullptr;
  7555. case GGML_OP_CONV_2D:
  7556. case GGML_OP_CONV_TRANSPOSE_2D:
  7557. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7558. uint32_t K = dst->ne[2]; // Cout
  7559. uint32_t NPQ = dst->ne[3] * dst->ne[1] * dst->ne[0]; // N * OH * OW
  7560. vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, K, NPQ);
  7561. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  7562. uint32_t KW = (uint32_t)src0->ne[0];
  7563. uint32_t KH = (uint32_t)src0->ne[1];
  7564. uint32_t s0 = (uint32_t)(ggml_get_op_params_i32(dst, 0));
  7565. uint32_t s1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 1) : s0;
  7566. uint32_t p0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0;
  7567. uint32_t p1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 3) : 0;
  7568. uint32_t d0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 4) : 1;
  7569. uint32_t d1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 5) : 1;
  7570. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7571. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7572. if (op == GGML_OP_CONV_2D) {
  7573. if (src0->type == GGML_TYPE_F32) {
  7574. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7575. } else if (src0->type == GGML_TYPE_F16) {
  7576. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7577. }
  7578. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7579. if (src0->type == GGML_TYPE_F32) {
  7580. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7581. } else if (src0->type == GGML_TYPE_F16) {
  7582. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7583. }
  7584. }
  7585. vk_pipeline pipeline = nullptr;
  7586. {
  7587. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7588. auto it = pipelines->find(conv2d_pipeline_state);
  7589. if (it != pipelines->end()) {
  7590. pipeline = it->second;
  7591. } else {
  7592. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7593. }
  7594. }
  7595. return pipeline;
  7596. }
  7597. return nullptr;
  7598. case GGML_OP_CONV_2D_DW:
  7599. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7600. if (ggml_is_contiguous(src1)) {
  7601. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7602. } else if (ggml_is_contiguous_channels(src1)) {
  7603. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7604. }
  7605. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7606. if (ggml_is_contiguous(src1)) {
  7607. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7608. } else if (ggml_is_contiguous_channels(src1)) {
  7609. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7610. }
  7611. }
  7612. return nullptr;
  7613. case GGML_OP_ADD1:
  7614. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7615. return ctx->device->pipeline_add1_f16_f16;
  7616. }
  7617. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7618. return ctx->device->pipeline_add1_f16_f32;
  7619. }
  7620. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7621. return ctx->device->pipeline_add1_f32_f32;
  7622. }
  7623. return nullptr;
  7624. case GGML_OP_ARANGE:
  7625. if (dst->type == GGML_TYPE_F32) {
  7626. return ctx->device->pipeline_arange_f32;
  7627. }
  7628. return nullptr;
  7629. case GGML_OP_FILL:
  7630. if (dst->type == GGML_TYPE_F32) {
  7631. return ctx->device->pipeline_fill_f32;
  7632. }
  7633. return nullptr;
  7634. default:
  7635. return nullptr;
  7636. }
  7637. GGML_UNUSED(src2);
  7638. }
  7639. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_unary_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7640. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7641. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7642. p.misalign_offsets = (a_offset << 16) | d_offset;
  7643. GGML_UNUSED(src1);
  7644. GGML_UNUSED(src2);
  7645. GGML_UNUSED(src3);
  7646. }
  7647. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_sum_rows_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7648. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7649. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7650. p.misalign_offsets = (a_offset << 16) | d_offset;
  7651. GGML_UNUSED(src1);
  7652. GGML_UNUSED(src2);
  7653. GGML_UNUSED(src3);
  7654. }
  7655. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_pad_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7656. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7657. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7658. p.misalign_offsets = (a_offset << 16) | d_offset;
  7659. GGML_UNUSED(src1);
  7660. GGML_UNUSED(src2);
  7661. GGML_UNUSED(src3);
  7662. }
  7663. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_im2col_3d_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7664. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7665. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7666. p.misalign_offsets = (a_offset << 16) | d_offset;
  7667. GGML_UNUSED(src0);
  7668. GGML_UNUSED(src2);
  7669. GGML_UNUSED(src3);
  7670. }
  7671. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_binary_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7672. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7673. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7674. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7675. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7676. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7677. GGML_UNUSED(src2);
  7678. GGML_UNUSED(src3);
  7679. }
  7680. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_upscale_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7681. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7682. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7683. p.a_offset = a_offset;
  7684. p.d_offset = d_offset;
  7685. GGML_UNUSED(src1);
  7686. GGML_UNUSED(src2);
  7687. GGML_UNUSED(src3);
  7688. }
  7689. template<typename PC>
  7690. static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst, ggml_op op, PC&& pc) {
  7691. 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];
  7692. if (src1 != nullptr) {
  7693. 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];
  7694. }
  7695. if (src2 != nullptr) {
  7696. 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];
  7697. }
  7698. if (src3 != nullptr) {
  7699. std::cerr << "), (" << src3 << ", name=" << src3->name << ", type=" << src3->type << ", ne0=" << src3->ne[0] << ", ne1=" << src3->ne[1] << ", ne2=" << src3->ne[2] << ", ne3=" << src3->ne[3] << ", nb0=" << src3->nb[0] << ", nb1=" << src3->nb[1] << ", nb2=" << src3->nb[2] << ", nb3=" << src3->nb[3];
  7700. }
  7701. 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];
  7702. std::cerr << "), " << ggml_op_name(op) << ")");
  7703. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7704. GGML_ASSERT(dst->buffer != nullptr);
  7705. const uint64_t ne00 = src0->ne[0];
  7706. const uint64_t ne01 = src0->ne[1];
  7707. const uint64_t ne02 = src0->ne[2];
  7708. const uint64_t ne03 = src0->ne[3];
  7709. const bool use_src1 = src1 != nullptr;
  7710. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7711. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7712. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7713. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7714. const bool use_src2 = src2 != nullptr;
  7715. const bool use_src3 = src3 != nullptr;
  7716. init_pushconst_fastdiv(pc);
  7717. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7718. if (pipeline == nullptr) {
  7719. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7720. if (src1 != nullptr) {
  7721. std::cerr << " and " << ggml_type_name(src1->type);
  7722. }
  7723. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7724. GGML_ABORT("fatal error");
  7725. }
  7726. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7727. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true);
  7728. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, true) : vk_subbuffer{};
  7729. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, true) : vk_subbuffer{};
  7730. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, true) : vk_subbuffer{};
  7731. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
  7732. // Compute misalignment offset for descriptors and store it in in push constants.
  7733. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7734. std::array<uint32_t, 3> elements;
  7735. switch (op) {
  7736. case GGML_OP_NORM:
  7737. case GGML_OP_RMS_NORM_BACK:
  7738. case GGML_OP_L2_NORM:
  7739. case GGML_OP_SOFT_MAX:
  7740. case GGML_OP_SOFT_MAX_BACK:
  7741. case GGML_OP_SUM_ROWS:
  7742. case GGML_OP_CUMSUM:
  7743. case GGML_OP_MEAN:
  7744. case GGML_OP_ARGMAX:
  7745. {
  7746. const uint32_t nr = ggml_nrows(src0);
  7747. if (nr > 262144) {
  7748. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7749. } else if (nr > 512) {
  7750. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7751. } else {
  7752. elements = { nr, 1, 1 };
  7753. }
  7754. } break;
  7755. case GGML_OP_SOLVE_TRI:
  7756. {
  7757. uint32_t nr = (uint32_t)(ne02 * ne03);
  7758. if (nr > 262144) {
  7759. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7760. } else if (nr > 512) {
  7761. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7762. } else {
  7763. elements = { nr, 1, 1 };
  7764. }
  7765. }
  7766. break;
  7767. case GGML_OP_RMS_NORM:
  7768. if (ctx->do_add_rms_partials) {
  7769. // Run one element per thread, 128 threads per workgroup
  7770. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7771. } else {
  7772. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7773. }
  7774. break;
  7775. case GGML_OP_SUM:
  7776. // We use GGML_OP_SUM_ROWS with 1 row.
  7777. elements = { 1, 1, 1 };
  7778. break;
  7779. case GGML_OP_GROUP_NORM:
  7780. {
  7781. const uint32_t num_groups = dst->op_params[0];
  7782. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7783. } break;
  7784. case GGML_OP_DIAG_MASK_INF:
  7785. case GGML_OP_ROPE:
  7786. case GGML_OP_ROPE_BACK:
  7787. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7788. break;
  7789. case GGML_OP_GET_ROWS:
  7790. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7791. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7792. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7793. break;
  7794. case GGML_OP_ARGSORT:
  7795. GGML_ASSERT(0);
  7796. break;
  7797. case GGML_OP_IM2COL:
  7798. {
  7799. const bool is_2D = dst->op_params[6] == 1;
  7800. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7801. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7802. const uint32_t KW = src0->ne[0];
  7803. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7804. const uint32_t OW = dst->ne[1];
  7805. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7806. elements = { OW * KW * KH, OH, batch * IC };
  7807. } break;
  7808. case GGML_OP_IM2COL_3D:
  7809. {
  7810. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7811. const uint32_t N = ne13 / IC;
  7812. const uint32_t KD = ne02;
  7813. const uint32_t KH = ne01;
  7814. const uint32_t KW = ne00;
  7815. const uint32_t OD = dst->ne[3] / N;
  7816. const uint32_t OH = dst->ne[2];
  7817. const uint32_t OW = dst->ne[1];
  7818. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7819. const uint32_t N_OD_OH = N*OD*OH;
  7820. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7821. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7822. } break;
  7823. case GGML_OP_TIMESTEP_EMBEDDING:
  7824. {
  7825. const uint32_t dim = dst->op_params[0];
  7826. uint32_t half_ceil = (dim + 1) / 2;
  7827. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7828. } break;
  7829. case GGML_OP_CONV_TRANSPOSE_1D:
  7830. {
  7831. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7832. } break;
  7833. case GGML_OP_POOL_2D:
  7834. {
  7835. const uint32_t N = dst->ne[3];
  7836. const uint32_t OC = dst->ne[2];
  7837. const uint32_t OH = dst->ne[1];
  7838. const uint32_t OW = dst->ne[0];
  7839. elements = { N * OC * OH * OW, 1, 1};
  7840. } break;
  7841. case GGML_OP_CONV_2D:
  7842. case GGML_OP_CONV_TRANSPOSE_2D:
  7843. if constexpr (std::is_same_v<PC, vk_op_conv2d_push_constants>) {
  7844. const uint32_t NPQ = pc.N * pc.OH * pc.OW;
  7845. const vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, pc.Cout, NPQ);
  7846. const uint32_t NPQ_blocks = CEIL_DIV(NPQ, vk_conv_block_sizes[shape].NPQ);
  7847. elements = { pc.Cout, NPQ_blocks, 1 };
  7848. if (elements[1] > 512) {
  7849. elements[2] = CEIL_DIV(elements[1], 512);
  7850. elements[1] = 512;
  7851. }
  7852. } else {
  7853. GGML_ABORT("invalid push constant type for CONV_2D");
  7854. }
  7855. break;
  7856. case GGML_OP_ADD:
  7857. case GGML_OP_SUB:
  7858. case GGML_OP_DIV:
  7859. case GGML_OP_MUL:
  7860. case GGML_OP_ADD1:
  7861. case GGML_OP_ARANGE:
  7862. case GGML_OP_FILL:
  7863. case GGML_OP_SCALE:
  7864. case GGML_OP_SQR:
  7865. case GGML_OP_SQRT:
  7866. case GGML_OP_SIN:
  7867. case GGML_OP_COS:
  7868. case GGML_OP_LOG:
  7869. case GGML_OP_TRI:
  7870. case GGML_OP_DIAG:
  7871. case GGML_OP_CLAMP:
  7872. case GGML_OP_PAD:
  7873. case GGML_OP_ROLL:
  7874. case GGML_OP_REPEAT:
  7875. case GGML_OP_REPEAT_BACK:
  7876. case GGML_OP_CPY:
  7877. case GGML_OP_CONCAT:
  7878. case GGML_OP_UPSCALE:
  7879. case GGML_OP_UNARY:
  7880. case GGML_OP_GLU:
  7881. case GGML_OP_CONV_2D_DW:
  7882. {
  7883. uint32_t ne = ggml_nelements(dst);
  7884. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7885. // Convert from number of logical elements to 2- or 4-byte units.
  7886. ne /= ggml_blck_size(src0->type);
  7887. if ((ggml_type_size(src0->type) % 4) == 0) {
  7888. ne *= ggml_type_size(src0->type) / 4;
  7889. } else {
  7890. ne *= ggml_type_size(src0->type) / 2;
  7891. }
  7892. }
  7893. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7894. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7895. // So divide by block size here before splitting into 512x512 groups.
  7896. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7897. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7898. }
  7899. if (ne > 262144) {
  7900. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7901. } else if (ne > 512) {
  7902. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7903. } else {
  7904. elements = { ne, 1, 1 };
  7905. }
  7906. if (pipeline == ctx->device->pipeline_cpy_transpose_32 ||
  7907. pipeline == ctx->device->pipeline_cpy_transpose_16) {
  7908. // 32x32 tiles
  7909. elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32);
  7910. elements[1] = (uint32_t)CEIL_DIV(dst->ne[1], 32);
  7911. elements[2] = (uint32_t)(dst->ne[2]*dst->ne[3]);
  7912. elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]);
  7913. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7914. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7915. }
  7916. } break;
  7917. case GGML_OP_ADD_ID:
  7918. {
  7919. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7920. } break;
  7921. case GGML_OP_SET_ROWS:
  7922. {
  7923. uint32_t ne = ggml_nelements(src0);
  7924. if (ggml_is_quantized(dst->type)) {
  7925. // quants run 32 threads each doing QUANT_K elements
  7926. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7927. } else {
  7928. // scalar types do one element per thread, running 512 threads
  7929. ne = CEIL_DIV(ne, 512);
  7930. }
  7931. if (ne > 262144) {
  7932. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7933. } else if (ne > 512) {
  7934. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7935. } else {
  7936. elements = { ne, 1, 1 };
  7937. }
  7938. }
  7939. break;
  7940. case GGML_OP_SSM_CONV:
  7941. {
  7942. const uint32_t nr = src0->ne[1];
  7943. const uint32_t n_t = dst->ne[1];
  7944. const uint32_t n_s = dst->ne[2];
  7945. elements = { nr, n_t, n_s };
  7946. }
  7947. break;
  7948. default:
  7949. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7950. break;
  7951. }
  7952. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7953. vk_subbuffer a_buf = src0_buf;
  7954. if (ctx->do_add_rms_partials) {
  7955. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  7956. }
  7957. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7958. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  7959. } else if (op == GGML_OP_GLU) {
  7960. // Empty src1 is possible in glu, but the shader needs a buffer
  7961. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7962. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  7963. } else if (op == GGML_OP_SOFT_MAX) {
  7964. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7965. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7966. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7967. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  7968. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7969. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  7970. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7971. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  7972. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  7973. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7974. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7975. // buffer device address path doesn't use dst buffer
  7976. dst_buf.size = 1;
  7977. }
  7978. // im2col uses only src1 and dst buffers
  7979. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  7980. } else if (op == GGML_OP_COUNT_EQUAL) {
  7981. // count_equal assumes that destination buffer is initialized with zeroes
  7982. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  7983. ggml_vk_sync_buffers(ctx, subctx);
  7984. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7985. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7986. // OPT_STEP_SGD works on src0, it does not need dst
  7987. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  7988. } else if (use_src3) {
  7989. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  7990. } else if (use_src2) {
  7991. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  7992. } else if (use_src1) {
  7993. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7994. } else {
  7995. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  7996. }
  7997. }
  7998. 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) {
  7999. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8000. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8001. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8002. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  8003. (uint32_t)ggml_nelements(src0),
  8004. (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,
  8005. (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,
  8006. (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,
  8007. 0,
  8008. 0.0f, 0.0f, 0,
  8009. });
  8010. }
  8011. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8012. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8013. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8014. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8015. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  8016. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  8017. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  8018. int offset = dst->op_params[3] / 4; // offset in bytes
  8019. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  8020. (uint32_t)ggml_nelements(src0),
  8021. (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,
  8022. (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,
  8023. (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,
  8024. 0,
  8025. 0.0f, 0.0f, offset,
  8026. });
  8027. }
  8028. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8029. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  8030. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  8031. // Make a list of all the tensors used by the op.
  8032. // Last element of the list is the dest tensor.
  8033. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  8034. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  8035. uint32_t num_tensors = num_srcs + 1;
  8036. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  8037. tensors[0] = first_node->src[0];
  8038. tensors[1] = first_node->src[1];
  8039. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  8040. // check whether the previous result is src[0] or src[1]
  8041. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  8042. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  8043. } else {
  8044. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  8045. }
  8046. }
  8047. tensors[num_srcs] = dst;
  8048. vk_op_multi_add_push_constants pc;
  8049. pc.ne20 = (uint32_t)dst->ne[0];
  8050. pc.ne21 = (uint32_t)dst->ne[1];
  8051. pc.ne22 = (uint32_t)dst->ne[2];
  8052. pc.ne23 = (uint32_t)dst->ne[3];
  8053. for (uint32_t i = 0; i < num_tensors; ++i) {
  8054. const ggml_tensor *t = tensors[i];
  8055. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  8056. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  8057. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  8058. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  8059. }
  8060. pc.rms_partials = ctx->do_add_rms_partials;
  8061. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  8062. if (pipeline == nullptr) {
  8063. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  8064. GGML_ABORT("fatal error");
  8065. }
  8066. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8067. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  8068. vk_buffer buf[MAX_PARAMETER_COUNT];
  8069. size_t offset[MAX_PARAMETER_COUNT];
  8070. bool uma[MAX_PARAMETER_COUNT];
  8071. for (uint32_t i = 0; i < num_tensors; ++i) {
  8072. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8073. buf[i] = nullptr;
  8074. offset[i] = 0;
  8075. uma[i] = false;
  8076. if (ctx->device->uma) {
  8077. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8078. uma[i] = buf[i] != nullptr;
  8079. }
  8080. if (!uma[i]) {
  8081. buf[i] = buf_ctx[i]->dev_buffer;
  8082. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8083. }
  8084. GGML_ASSERT(buf[i] != nullptr);
  8085. }
  8086. // If any remaining descriptors are unused, just point them at src[0]
  8087. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  8088. buf[i] = buf[0];
  8089. offset[i] = 0;
  8090. }
  8091. if (ctx->do_add_rms_partials) {
  8092. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  8093. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  8094. }
  8095. std::array<uint32_t, 3> elements;
  8096. uint32_t ne = ggml_nelements(dst);
  8097. if (ne > 262144) {
  8098. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8099. } else if (ne > 512) {
  8100. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8101. } else {
  8102. elements = { ne, 1, 1 };
  8103. }
  8104. static_assert(MAX_PARAMETER_COUNT == 12);
  8105. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8106. {
  8107. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8108. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8109. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8110. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8111. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8112. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8113. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8114. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  8115. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  8116. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  8117. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  8118. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  8119. }, pc, elements);
  8120. }
  8121. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8122. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8123. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8124. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8125. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  8126. (uint32_t)ggml_nelements(src0),
  8127. (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,
  8128. (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,
  8129. (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,
  8130. 0,
  8131. 0.0f, 0.0f, ctx->do_add_rms_partials,
  8132. });
  8133. }
  8134. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8135. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8136. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8137. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8138. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  8139. (uint32_t)ggml_nelements(src0),
  8140. (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,
  8141. (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,
  8142. (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,
  8143. 0,
  8144. 0.0f, 0.0f, 0,
  8145. });
  8146. }
  8147. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8148. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8149. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8150. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8151. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  8152. (uint32_t)ggml_nelements(src0),
  8153. (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,
  8154. (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,
  8155. (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,
  8156. 0,
  8157. 0.0f, 0.0f, 0,
  8158. });
  8159. }
  8160. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8161. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8162. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8163. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8164. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  8165. (uint32_t)ggml_nelements(src0),
  8166. (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,
  8167. (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,
  8168. (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,
  8169. 0,
  8170. 0.0f, 0.0f, 0,
  8171. });
  8172. }
  8173. static void ggml_vk_add_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  8174. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8175. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8176. const uint32_t src2_type_size = ggml_type_size(src2->type);
  8177. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  8178. (uint32_t)dst->ne[0],
  8179. (uint32_t)dst->ne[1],
  8180. (uint32_t)src0->nb[1] / src0_type_size,
  8181. (uint32_t)src0->nb[2] / src0_type_size,
  8182. (uint32_t)src1->nb[1] / src1_type_size,
  8183. (uint32_t)src2->nb[1] / src2_type_size,
  8184. });
  8185. }
  8186. static void ggml_vk_op_f32_wkv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_rwkv_wkv6_push_constants&& pc, int version) {
  8187. GGML_ASSERT(version == 6 || version == 7);
  8188. int num_srcs = version == 6 ? 6 : 7;
  8189. for (int i = 0; i < num_srcs; i++) {
  8190. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  8191. }
  8192. GGML_ASSERT(dst->buffer != nullptr);
  8193. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8194. GGML_ASSERT(pipeline != nullptr);
  8195. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8196. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8197. vk_subbuffer src_buf[7] = {};
  8198. for (int i = 0; i < num_srcs; i++) {
  8199. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8200. }
  8201. std::array<uint32_t, 3> elements = {
  8202. (uint32_t)(pc.B * pc.H),
  8203. 1,
  8204. 1
  8205. };
  8206. if (version == 6) {
  8207. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8208. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  8209. pc, elements);
  8210. } else if (version == 7) {
  8211. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8212. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8213. pc, elements);
  8214. } else {
  8215. // shouldn't happen
  8216. GGML_ASSERT(false);
  8217. }
  8218. }
  8219. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8220. const size_t seq_length = dst->src[0]->ne[2];
  8221. const size_t n_embed = dst->ne[0];
  8222. const size_t n_heads = dst->src[0]->ne[1];
  8223. const size_t n_seqs = dst->src[5]->ne[1];
  8224. ggml_vk_op_f32_wkv(
  8225. ctx, subctx, dst,
  8226. {
  8227. (uint32_t)n_seqs,
  8228. (uint32_t)seq_length,
  8229. (uint32_t)n_embed,
  8230. (uint32_t)n_heads,
  8231. },
  8232. 6
  8233. );
  8234. }
  8235. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8236. const size_t seq_length = dst->src[0]->ne[2];
  8237. const size_t n_embed = dst->ne[0];
  8238. const size_t n_heads = dst->src[0]->ne[1];
  8239. const size_t n_seqs = dst->src[6]->ne[1];
  8240. ggml_vk_op_f32_wkv(
  8241. ctx, subctx, dst,
  8242. {
  8243. (uint32_t)n_seqs,
  8244. (uint32_t)seq_length,
  8245. (uint32_t)n_embed,
  8246. (uint32_t)n_heads,
  8247. },
  8248. 7
  8249. );
  8250. }
  8251. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8252. const ggml_tensor * src0 = dst->src[0];
  8253. const ggml_tensor * src1 = dst->src[1];
  8254. const ggml_tensor * src2 = dst->src[2];
  8255. const ggml_tensor * src3 = dst->src[3];
  8256. const ggml_tensor * src4 = dst->src[4];
  8257. const ggml_tensor * src5 = dst->src[5];
  8258. GGML_ASSERT(dst->buffer != nullptr);
  8259. const uint32_t head_dim = src0->ne[1];
  8260. const uint32_t n_head = src1->ne[1];
  8261. const uint32_t n_group = src4->ne[1];
  8262. const uint32_t n_tok = src1->ne[2];
  8263. const uint32_t n_seq = src1->ne[3];
  8264. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8265. GGML_ASSERT(is_mamba2);
  8266. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8267. GGML_ASSERT(pipeline != nullptr);
  8268. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8269. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8270. const vk_op_ssm_scan_push_constants pc = {
  8271. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8272. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8273. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8274. (uint32_t)src3->nb[1],
  8275. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8276. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8277. (uint32_t)s_off,
  8278. n_head, head_dim, n_group, n_tok
  8279. };
  8280. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8281. vk_subbuffer src_buf[7] = {};
  8282. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8283. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8284. }
  8285. std::array<uint32_t, 3> elements;
  8286. const int splitH = 16;
  8287. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8288. const uint32_t num_workgroups_y = n_seq;
  8289. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8290. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8291. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8292. pc, elements);
  8293. }
  8294. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8295. const ggml_tensor * src0 = dst->src[0];
  8296. const ggml_tensor * src1 = dst->src[1];
  8297. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8298. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8299. (uint32_t)src1->nb[1],
  8300. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8301. (uint32_t)src1->ne[0],
  8302. (uint32_t)src0->ne[0],
  8303. (uint32_t)src0->ne[1],
  8304. (uint32_t)dst->ne[1],
  8305. (uint32_t)dst->ne[2],
  8306. });
  8307. }
  8308. static void ggml_vk_op_f32_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_push_constants&& pc) {
  8309. const ggml_tensor * x = dst->src[0];
  8310. const ggml_tensor * g = dst->src[1];
  8311. const ggml_tensor * gm = dst->src[2];
  8312. const ggml_tensor * gv = dst->src[3];
  8313. const ggml_tensor * p = dst->src[4];
  8314. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8315. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8316. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8317. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8318. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8319. GGML_ASSERT(dst->buffer != nullptr);
  8320. GGML_ASSERT(ggml_is_contiguous(x));
  8321. GGML_ASSERT(ggml_is_contiguous(g));
  8322. GGML_ASSERT(ggml_is_contiguous(gm));
  8323. GGML_ASSERT(ggml_is_contiguous(gv));
  8324. GGML_ASSERT(ggml_is_contiguous(p));
  8325. GGML_ASSERT(ggml_are_same_shape(x, g));
  8326. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8327. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8328. GGML_ASSERT(ggml_nelements(p) == 7);
  8329. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8330. GGML_ASSERT(pipeline != nullptr);
  8331. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8332. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8333. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8334. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8335. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8336. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8337. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8338. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8339. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8340. pc, elements);
  8341. }
  8342. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8343. const size_t n = ggml_nelements(dst->src[0]);
  8344. ggml_vk_op_f32_opt_step_adamw(
  8345. ctx, subctx, dst,
  8346. { (uint32_t)n, 0, 0.0f, 0.0f }
  8347. );
  8348. }
  8349. static void ggml_vk_opt_step_sgd(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  8350. const size_t n = ggml_nelements(dst->src[0]);
  8351. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_OPT_STEP_SGD, { (uint32_t)n, 0, 0.0f, 0.0f });
  8352. }
  8353. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8354. int * op_params = (int *)dst->op_params;
  8355. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8356. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8357. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8358. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8359. (uint32_t)ggml_nelements(dst),
  8360. (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,
  8361. (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,
  8362. (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,
  8363. 0,
  8364. 0.0f, 0.0f, op_params[0],
  8365. });
  8366. }
  8367. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8368. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8369. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8370. GGML_TENSOR_UNARY_OP_LOCALS
  8371. float sf0 = (float)ne0 / ne00;
  8372. float sf1 = (float)ne1 / ne01;
  8373. float sf2 = (float)ne2 / ne02;
  8374. float sf3 = (float)ne3 / ne03;
  8375. float pixel_offset = 0.5f;
  8376. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8377. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8378. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8379. pixel_offset = 0.0f;
  8380. }
  8381. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8382. (uint32_t)ggml_nelements(dst), 0, 0,
  8383. (uint32_t)ne00, (uint32_t)ne01,
  8384. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8385. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8386. sf0, sf1, sf2, sf3, pixel_offset
  8387. });
  8388. }
  8389. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8390. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8391. p.param1 = ggml_get_op_params_f32(dst, 0);
  8392. p.param2 = ggml_get_op_params_f32(dst, 1);
  8393. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8394. }
  8395. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8396. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8397. }
  8398. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8399. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8400. }
  8401. static void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8402. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8403. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8404. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8405. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, {
  8406. (uint32_t)ggml_nelements(src0),
  8407. (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,
  8408. (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,
  8409. (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,
  8410. 0,
  8411. 0.0f, 0.0f, 0,
  8412. });
  8413. }
  8414. static void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8415. VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8416. vk_op_push_constants pc = {
  8417. (uint32_t)ggml_nelements(dst),
  8418. 1,
  8419. ggml_get_op_params_f32(dst, 0),
  8420. ggml_get_op_params_f32(dst, 2),
  8421. };
  8422. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_ARANGE);
  8423. GGML_ASSERT(pipeline != nullptr);
  8424. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8425. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8426. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8427. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8428. }
  8429. static void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8430. VK_LOG_DEBUG("ggml_vk_fill(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8431. vk_op_push_constants pc = {
  8432. (uint32_t)ggml_nelements(dst),
  8433. 1,
  8434. ggml_get_op_params_f32(dst, 0),
  8435. 0.0f,
  8436. };
  8437. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_FILL);
  8438. GGML_ASSERT(pipeline != nullptr);
  8439. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8440. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8441. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8442. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8443. }
  8444. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8445. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8446. }
  8447. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8448. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8449. }
  8450. static void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8451. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst));
  8452. }
  8453. static void ggml_vk_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8454. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8455. p.param1 = ggml_get_op_params_f32(dst, 0);
  8456. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TRI, std::move(p));
  8457. }
  8458. static void ggml_vk_diag(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8459. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8460. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG, std::move(p));
  8461. }
  8462. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8463. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8464. p.param1 = ggml_get_op_params_f32(dst, 0);
  8465. p.param2 = ggml_get_op_params_f32(dst, 1);
  8466. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8467. }
  8468. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8469. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8470. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8471. }
  8472. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8473. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8474. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8475. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8476. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8477. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8478. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8479. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8480. memcpy(&p.param1, &s01_packed, sizeof(float));
  8481. memcpy(&p.param2, &s23_packed, sizeof(float));
  8482. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8483. }
  8484. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8485. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8486. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8487. }
  8488. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8489. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8490. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8491. }
  8492. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8493. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8494. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8495. // Convert from number of logical elements to 2- or 4-byte units.
  8496. ne /= ggml_blck_size(src0->type);
  8497. if ((ggml_type_size(src0->type) % 4) == 0) {
  8498. ne *= ggml_type_size(src0->type) / 4;
  8499. } else {
  8500. ne *= ggml_type_size(src0->type) / 2;
  8501. }
  8502. }
  8503. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8504. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8505. }
  8506. static void ggml_vk_set_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8507. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8508. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8509. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8510. // Skip empty skip_rows operations. For most ops the empty check at the start
  8511. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8512. // with empty srcs.
  8513. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8514. return;
  8515. }
  8516. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8517. (uint32_t)ggml_nelements(src0),
  8518. (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,
  8519. (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,
  8520. (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,
  8521. 0,
  8522. 0.0f, 0.0f, 0,
  8523. });
  8524. }
  8525. static void ggml_vk_silu_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8526. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SILU_BACK, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  8527. }
  8528. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8529. float * op_params = (float *)dst->op_params;
  8530. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8531. }
  8532. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8533. const int * int_op_params = (const int *)dst->op_params;
  8534. const float * float_op_params = (const float *)dst->op_params;
  8535. const uint32_t num_groups = int_op_params[0];
  8536. const float eps = float_op_params[1];
  8537. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8538. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f });
  8539. }
  8540. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8541. const uint32_t ne = (uint32_t)node->ne[0];
  8542. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8543. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8544. return num_partials;
  8545. }
  8546. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8547. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8548. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8549. return num_bytes;
  8550. }
  8551. static vk_op_rope_push_constants ggml_vk_make_rope_constants(const ggml_tensor *dst, const ggml_tensor *src0, const bool has_ff, bool backprop, const uint32_t set_rows_stride) {
  8552. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8553. const int mode = ((const int32_t *) dst->op_params)[2];
  8554. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8555. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8556. const float freq_base = ((const float *) dst->op_params)[5];
  8557. const float freq_scale = ((const float *) dst->op_params)[6];
  8558. const float ext_factor = ((const float *) dst->op_params)[7];
  8559. const float attn_factor = ((const float *) dst->op_params)[8];
  8560. const float beta_fast = ((const float *) dst->op_params)[9];
  8561. const float beta_slow = ((const float *) dst->op_params)[10];
  8562. int sections[4] {};
  8563. if (mode & GGML_ROPE_TYPE_MROPE) {
  8564. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8565. }
  8566. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8567. float corr_dims[2];
  8568. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8569. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8570. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8571. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8572. vk_op_rope_push_constants rope {
  8573. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8574. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8575. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8576. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8577. };
  8578. return rope;
  8579. }
  8580. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, float * op_params) {
  8581. ggml_tensor * dst;
  8582. const ggml_tensor * src0;
  8583. const ggml_tensor * src1;
  8584. if (ctx->num_additional_fused_ops > 0) {
  8585. // fused rms_norm + mul
  8586. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8587. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8588. dst = mul;
  8589. src0 = cgraph->nodes[node_idx]->src[0];
  8590. src1 = other_src;
  8591. } else {
  8592. dst = cgraph->nodes[node_idx];
  8593. src0 = src1 = dst->src[0];
  8594. }
  8595. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8596. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8597. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8598. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8599. vk_op_binary_push_constants bin {
  8600. (uint32_t)ggml_nelements(src0),
  8601. (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,
  8602. (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,
  8603. (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,
  8604. 0,
  8605. op_params[0], 0.0f, (int32_t)param3,
  8606. };
  8607. // more than one fused op means rms_norm+mul+rope
  8608. if (ctx->num_additional_fused_ops > 1) {
  8609. static constexpr uint32_t max_tensors = 7;
  8610. const ggml_tensor *tensors[max_tensors] {};
  8611. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8612. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8613. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8614. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8615. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8616. tensors[0] = rms->src[0];
  8617. tensors[1] = other_src;
  8618. tensors[2] = mul;
  8619. tensors[3] = rope->src[1]; // pos
  8620. tensors[4] = rope->src[2]; // ff
  8621. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8622. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8623. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8624. vk_op_rms_norm_mul_rope_push_constants pc;
  8625. pc.bin = bin;
  8626. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8627. vk_pipeline pipeline = tensors[5]->type == GGML_TYPE_F16 ? ctx->device->pipeline_rms_norm_mul_rope_f32_f16 : ctx->device->pipeline_rms_norm_mul_rope_f32_f32;
  8628. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8629. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8630. vk_buffer buf[max_tensors];
  8631. size_t offset[max_tensors];
  8632. bool uma[max_tensors];
  8633. for (uint32_t i = 0; i < max_tensors; ++i) {
  8634. if (!tensors[i]) {
  8635. // If any remaining descriptors are unused, just point them at src[0]
  8636. buf[i] = buf[0];
  8637. offset[i] = 0;
  8638. continue;
  8639. }
  8640. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8641. buf[i] = nullptr;
  8642. offset[i] = 0;
  8643. uma[i] = false;
  8644. if (ctx->device->uma) {
  8645. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8646. uma[i] = buf[i] != nullptr;
  8647. }
  8648. if (!uma[i]) {
  8649. buf[i] = buf_ctx[i]->dev_buffer;
  8650. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8651. }
  8652. GGML_ASSERT(buf[i] != nullptr);
  8653. }
  8654. std::array<uint32_t, 3> elements;
  8655. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8656. static_assert(max_tensors == 7);
  8657. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8658. {
  8659. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8660. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8661. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8662. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8663. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8664. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8665. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8666. }, pc, elements);
  8667. } else {
  8668. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8669. }
  8670. if (ctx->do_add_rms_partials_offset_calculation) {
  8671. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8672. ctx->do_add_rms_partials = false;
  8673. ctx->do_add_rms_partials_offset_calculation = false;
  8674. }
  8675. }
  8676. static void ggml_vk_rms_norm_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8677. float * op_params = (float *)dst->op_params;
  8678. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM_BACK, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8679. }
  8680. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8681. float * op_params = (float *)dst->op_params;
  8682. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_L2_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8683. }
  8684. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8685. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  8686. }
  8687. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8688. const float * op_params_f = (const float *)dst->op_params;
  8689. const bool swapped = (bool)dst->op_params[1];
  8690. const bool split = src1 != nullptr;
  8691. const float alpha = op_params_f[2];
  8692. const float limit = op_params_f[3];
  8693. GGML_ASSERT(ggml_is_contiguous(src0));
  8694. if (!split) {
  8695. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8696. } else {
  8697. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8698. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8699. GGML_ASSERT(src0->type == src1->type);
  8700. }
  8701. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8702. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8703. {
  8704. (uint32_t)ggml_nelements(dst),
  8705. (uint32_t)src0->ne[0],
  8706. (uint32_t)dst->ne[0],
  8707. mode,
  8708. alpha,
  8709. limit
  8710. });
  8711. }
  8712. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8713. int32_t * op_params = (int32_t *)dst->op_params;
  8714. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] });
  8715. }
  8716. static void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  8717. float * op_params = (float *)dst->op_params;
  8718. float scale = op_params[0];
  8719. float max_bias = op_params[1];
  8720. const uint32_t ncols = (uint32_t)src0->ne[0];
  8721. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8722. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8723. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8724. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8725. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8726. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8727. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8728. const uint32_t n_head_kv = src0->ne[2];
  8729. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8730. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8731. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8732. vk_op_soft_max_push_constants pc {
  8733. ncols,
  8734. src1 != nullptr ? nrows_y : (uint32_t)0,
  8735. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8736. ne12, ne13,
  8737. nb11, nb12, nb13,
  8738. scale, max_bias,
  8739. m0, m1,
  8740. n_head_log2,
  8741. nrows_x,
  8742. src2 != nullptr
  8743. };
  8744. if (ncols <= 16384) {
  8745. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, std::move(pc));
  8746. } else {
  8747. vk_subbuffer buf_a = ggml_vk_tensor_subbuffer(ctx, src0);
  8748. vk_subbuffer buf_b = src1 ? ggml_vk_tensor_subbuffer(ctx, src1) : buf_a;
  8749. vk_subbuffer buf_c = src2 ? ggml_vk_tensor_subbuffer(ctx, src2) : buf_a;
  8750. vk_subbuffer buf_d = ggml_vk_tensor_subbuffer(ctx, dst);
  8751. uint32_t elems_per_wg = 128 * 4;
  8752. uint32_t num_wgs = CEIL_DIV(ncols, elems_per_wg);
  8753. size_t tmp_size = num_wgs * nrows_x * sizeof(float);
  8754. if (ctx->prealloc_size_x < tmp_size) {
  8755. ctx->prealloc_size_x = tmp_size;
  8756. ggml_vk_preallocate_buffers(ctx, subctx);
  8757. }
  8758. if (ctx->prealloc_size_y < tmp_size) {
  8759. ctx->prealloc_size_y = tmp_size;
  8760. ggml_vk_preallocate_buffers(ctx, subctx);
  8761. }
  8762. if (ctx->prealloc_x_need_sync || ctx->prealloc_y_need_sync) {
  8763. ggml_vk_sync_buffers(ctx, subctx);
  8764. }
  8765. vk_subbuffer buf_x = { ctx->prealloc_x, 0, tmp_size };
  8766. vk_subbuffer buf_y = { ctx->prealloc_y, 0, tmp_size };
  8767. std::array<uint32_t, 3> elements = { num_wgs, nrows_x, 1 };
  8768. vk_pipeline pipeline1 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large1_f32_f16 : ctx->device->pipeline_soft_max_large1_f32;
  8769. vk_pipeline pipeline2 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large2_f32_f16 : ctx->device->pipeline_soft_max_large2_f32;
  8770. vk_pipeline pipeline3 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large3_f32_f16 : ctx->device->pipeline_soft_max_large3_f32;
  8771. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  8772. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  8773. ggml_pipeline_request_descriptor_sets(ctx, pipeline3, 1);
  8774. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8775. ggml_vk_sync_buffers(ctx, subctx);
  8776. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8777. ggml_vk_sync_buffers(ctx, subctx);
  8778. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline3, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8779. ctx->prealloc_x_need_sync = true;
  8780. ctx->prealloc_y_need_sync = true;
  8781. }
  8782. }
  8783. static void ggml_vk_soft_max_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8784. float * op_params = (float *)dst->op_params;
  8785. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOFT_MAX_BACK, { (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), op_params[0], op_params[1] });
  8786. }
  8787. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8788. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8789. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8790. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8791. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8792. cgraph->nodes[node_idx + 5];
  8793. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8794. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8795. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8796. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8797. const int n_experts = logits->ne[0];
  8798. const int n_rows = logits->ne[1];
  8799. const int n_expert_used = weights->ne[1];
  8800. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8801. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8802. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8803. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  8804. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  8805. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  8806. vk_op_topk_moe_push_constants pc {};
  8807. pc.n_rows = n_rows;
  8808. pc.n_experts_push = n_experts;
  8809. pc.n_expert_used = n_expert_used;
  8810. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8811. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8812. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8813. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8814. }
  8815. GGML_ASSERT(n_expert_used <= n_experts);
  8816. const uint32_t rows_per_block = 4;
  8817. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8818. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, weights_buf, ids_buf}, pc, elements);
  8819. }
  8820. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  8821. ggml_tensor * dst = cgraph->nodes[node_idx];
  8822. const ggml_tensor * src0 = dst->src[0];
  8823. const ggml_tensor * src1 = dst->src[1];
  8824. const ggml_tensor * src2 = dst->src[2];
  8825. const ggml_tensor * src3 = nullptr;
  8826. const int n_dims = ((int32_t *) dst->op_params)[1];
  8827. const int mode = ((int32_t *) dst->op_params)[2];
  8828. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8829. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8830. const float freq_base = ((float *) dst->op_params)[5];
  8831. const float beta_fast = ((float *) dst->op_params)[9];
  8832. const float beta_slow = ((float *) dst->op_params)[10];
  8833. int sections[4] {};
  8834. if (mode & GGML_ROPE_TYPE_MROPE) {
  8835. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8836. }
  8837. float corr_dims[2];
  8838. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8839. uint32_t set_rows_stride = 0;
  8840. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8841. // and overrides the dst and sets src3=row_indices
  8842. if (ctx->num_additional_fused_ops > 0) {
  8843. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8844. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8845. dst = cgraph->nodes[node_idx + 2];
  8846. }
  8847. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  8848. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  8849. }
  8850. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8851. const uint32_t * op_params = (const uint32_t *)dst->op_params;
  8852. uint32_t ncols = src0->ne[0];
  8853. uint32_t nrows = ggml_nrows(src0);
  8854. uint32_t ncols_pad_log2 = (uint32_t)ceilf(log2f(float(ncols)));
  8855. uint32_t ncolsp2 = 1 << ncols_pad_log2;
  8856. vk_op_argsort_push_constants pc { ncols, ncolsp2, ncols_pad_log2, nrows, op_params[0], 0, 0, 0, 0, };
  8857. // Pick the largest workgroup size <= ncolsp2
  8858. uint32_t pipeline_idx = std::min(ncols_pad_log2, num_argsort_pipelines - 1);
  8859. // Use the "small" argsort shader if the whole sort can be done by a single workgroup.
  8860. bool use_small = ncols_pad_log2 <= ctx->device->max_workgroup_size_log2 &&
  8861. ctx->device->pipeline_argsort_f32[pipeline_idx] != nullptr;
  8862. vk_pipeline pipeline = use_small ? ctx->device->pipeline_argsort_f32[pipeline_idx]
  8863. : ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  8864. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  8865. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8866. vk_subbuffer subbuf1 = dst_buf;
  8867. // Reserve space for ivec2 per element, with rows padded to a power of two
  8868. if (!use_small) {
  8869. const size_t x_sz = size_t{ncolsp2} * nrows * 2 * sizeof(int);
  8870. if (ctx->prealloc_size_x < x_sz) {
  8871. ctx->prealloc_size_x = x_sz;
  8872. ggml_vk_preallocate_buffers(ctx, subctx);
  8873. }
  8874. if (ctx->prealloc_x_need_sync) {
  8875. ggml_vk_sync_buffers(ctx, subctx);
  8876. }
  8877. subbuf1 = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  8878. }
  8879. std::array<uint32_t, 3> elements;
  8880. elements[0] = ncolsp2;
  8881. elements[1] = std::min((uint32_t)ggml_nrows(src0), ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8882. elements[2] = 1;
  8883. // First dispatch initializes tmp_idx and does the first N passes where
  8884. // there is only communication between threads in the same workgroup.
  8885. {
  8886. vk_op_argsort_push_constants pc2 = pc;
  8887. pc2.outer_start = 0;
  8888. pc2.outer_end = std::min(ncols_pad_log2, ctx->device->max_workgroup_size_log2);
  8889. pc2.inner_start = 0;
  8890. pc2.inner_end = 100;
  8891. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8892. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  8893. }
  8894. if (!use_small) {
  8895. ggml_vk_sync_buffers(ctx, subctx);
  8896. // Loop over outer/inner passes, synchronizing between each pass.
  8897. for (uint32_t outer = ctx->device->max_workgroup_size_log2; outer < ncols_pad_log2; ++outer) {
  8898. for (uint32_t inner = 0; inner < outer + 1; ++inner) {
  8899. vk_op_argsort_push_constants pc2 = pc;
  8900. pc2.outer_start = outer;
  8901. pc2.outer_end = outer + 1;
  8902. pc2.inner_start = inner;
  8903. pc2.inner_end = inner + 1;
  8904. // When the inner idx is large enough, there's only communication
  8905. // within a workgroup. So the remaining inner iterations can all
  8906. // run in the same dispatch.
  8907. if (outer - inner < pipeline_idx) {
  8908. pc2.inner_end = 100;
  8909. inner = outer;
  8910. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  8911. } else {
  8912. // Smaller workgroup empirically seems to perform better
  8913. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx - 2];
  8914. }
  8915. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8916. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  8917. ggml_vk_sync_buffers(ctx, subctx);
  8918. }
  8919. }
  8920. ctx->prealloc_x_need_sync = true;
  8921. }
  8922. }
  8923. static void ggml_vk_topk(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8924. uint32_t ncols = src0->ne[0];
  8925. uint32_t nrows = ggml_nrows(src0);
  8926. uint32_t k = dst->ne[0];
  8927. vk_op_topk_push_constants pc { ncols, ncols, ncols, k, nrows, 0, 0 };
  8928. if (ctx->prealloc_x_need_sync) {
  8929. ggml_vk_sync_buffers(ctx, subctx);
  8930. }
  8931. std::array<uint32_t, 3> elements;
  8932. elements[1] = std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8933. elements[2] = 1;
  8934. uint32_t num_elements = ncols;
  8935. // Each iteration reduces a workgroup's worth of elements down to the K
  8936. // largest elements. Repeat until we have the top K elements.
  8937. // Need to do at least one iteration to write out the results.
  8938. bool done_one_iter = false;
  8939. uint32_t dbl_buf_index = 0;
  8940. size_t dbl_buf_size;
  8941. while (num_elements > k || !done_one_iter) {
  8942. // Prefer going as small as num_topk_pipelines - 3 for perf reasons.
  8943. // But if K is larger, then we need a larger workgroup
  8944. uint32_t max_pipeline = num_topk_pipelines - 1;
  8945. uint32_t preferred_pipeline = std::max(num_topk_pipelines - 3, (uint32_t)log2f(float(k)) + 2);
  8946. max_pipeline = std::min(preferred_pipeline, max_pipeline);
  8947. uint32_t min_pipeline = (uint32_t)log2f(float(k)) + 1;
  8948. // require full subgroup
  8949. min_pipeline = std::max(min_pipeline, ctx->device->subgroup_size_log2);
  8950. uint32_t pipeline_idx = (uint32_t)ceilf(log2f(float(num_elements)));
  8951. pipeline_idx = std::min(pipeline_idx, max_pipeline);
  8952. pipeline_idx = std::max(pipeline_idx, min_pipeline);
  8953. if (num_elements > (1u << pipeline_idx)) {
  8954. // If we could finish on this loop iteration (i.e. a single workgroup)
  8955. // then do so. It's better than the overhead of another pass.
  8956. for (uint32_t i = pipeline_idx; i < num_topk_pipelines; ++i) {
  8957. if (num_elements <= (1u << i)) {
  8958. pipeline_idx = i;
  8959. break;
  8960. }
  8961. }
  8962. }
  8963. vk_pipeline pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  8964. // If the device doesn't support a pipeline this large, use smaller
  8965. while (!pipeline) {
  8966. pipeline_idx--;
  8967. GGML_ASSERT(pipeline_idx >= min_pipeline);
  8968. pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  8969. }
  8970. vk_op_topk_push_constants pc2 = pc;
  8971. pc2.ncols_input = num_elements;
  8972. // Number of elements remaining after this pass
  8973. uint32_t num_dst_elements = (num_elements / pipeline->wg_denoms[0]) * k + std::min(k, num_elements % pipeline->wg_denoms[0]);
  8974. pc2.ncols_output = num_dst_elements;
  8975. if (!done_one_iter) {
  8976. // Reserve space for ivec2 per element, double buffered
  8977. // K per workgroup per row
  8978. dbl_buf_size = num_dst_elements * nrows * 2 * sizeof(int);
  8979. dbl_buf_size = ROUNDUP_POW2(dbl_buf_size, ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  8980. const size_t x_sz = dbl_buf_size * 2;
  8981. if (ctx->prealloc_size_x < x_sz) {
  8982. ctx->prealloc_size_x = x_sz;
  8983. ggml_vk_preallocate_buffers(ctx, subctx);
  8984. }
  8985. }
  8986. vk_subbuffer src_buf;
  8987. vk_subbuffer dst_buf;
  8988. if (num_elements == ncols) {
  8989. pc2.first_pass = 1;
  8990. src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  8991. } else {
  8992. src_buf = { ctx->prealloc_x, dbl_buf_index * dbl_buf_size, dbl_buf_size };
  8993. }
  8994. if (num_dst_elements == k) {
  8995. pc2.last_pass = 1;
  8996. dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8997. } else {
  8998. dst_buf = { ctx->prealloc_x, (dbl_buf_index ^ 1) * dbl_buf_size, dbl_buf_size };
  8999. }
  9000. elements[0] = num_elements;
  9001. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9002. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src_buf, dst_buf }, pc2, elements);
  9003. num_elements = num_dst_elements;
  9004. dbl_buf_index ^= 1;
  9005. if (num_elements > k) {
  9006. ggml_vk_sync_buffers(ctx, subctx);
  9007. }
  9008. done_one_iter = true;
  9009. }
  9010. ctx->prealloc_x_need_sync = true;
  9011. }
  9012. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9013. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  9014. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  9015. }
  9016. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9017. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9018. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  9019. }
  9020. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9021. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9022. p.weight = 1.0f / (float)src0->ne[0];
  9023. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  9024. }
  9025. static void ggml_vk_cumsum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9026. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9027. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CUMSUM, p);
  9028. }
  9029. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9030. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGMAX, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f });
  9031. }
  9032. static void ggml_vk_count_equal(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9033. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_COUNT_EQUAL, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  9034. }
  9035. static void ggml_vk_solve_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9036. const uint32_t src0_type_size = ggml_type_size(src0->type);
  9037. const uint32_t src1_type_size = ggml_type_size(src1->type);
  9038. const uint32_t dst_type_size = ggml_type_size(dst->type);
  9039. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOLVE_TRI, {
  9040. (uint32_t)ggml_nelements(src0),
  9041. (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,
  9042. (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,
  9043. (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,
  9044. 0,
  9045. 0.0f, 0.0f, 0,
  9046. });
  9047. }
  9048. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9049. const int32_t s0 = dst->op_params[0];
  9050. const int32_t s1 = dst->op_params[1];
  9051. const int32_t p0 = dst->op_params[2];
  9052. const int32_t p1 = dst->op_params[3];
  9053. const int32_t d0 = dst->op_params[4];
  9054. const int32_t d1 = dst->op_params[5];
  9055. const bool is_2D = dst->op_params[6] == 1;
  9056. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  9057. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  9058. const uint32_t IW = src1->ne[0];
  9059. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  9060. const uint32_t KW = src0->ne[0];
  9061. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  9062. const uint32_t OW = dst->ne[1];
  9063. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  9064. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  9065. const uint32_t pelements = OW * KW * KH;
  9066. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9067. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9068. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9069. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  9070. dst_addr,
  9071. batch_offset, offset_delta,
  9072. IC, IW, IH, OW, OH, KW, KH,
  9073. pelements,
  9074. IC * KH * KW,
  9075. s0, s1, p0, p1, d0, d1,
  9076. });
  9077. }
  9078. static void ggml_vk_im2col_3d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9079. GGML_TENSOR_BINARY_OP_LOCALS
  9080. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  9081. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  9082. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  9083. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  9084. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  9085. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  9086. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  9087. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  9088. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  9089. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  9090. const int64_t N = ne13 / IC;
  9091. const int64_t ID = ne12;
  9092. const int64_t IH = ne11;
  9093. const int64_t IW = ne10;
  9094. const int64_t KD = ne02;
  9095. const int64_t KH = ne01;
  9096. const int64_t KW = ne00;
  9097. const int64_t OD = ne3 / N;
  9098. const int64_t OH = ne2;
  9099. const int64_t OW = ne1;
  9100. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9101. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9102. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9103. vk_op_im2col_3d_push_constants pc {};
  9104. pc.dst_addr = dst_addr;
  9105. pc.nb10 = nb10 / ggml_type_size(src1->type);
  9106. pc.nb11 = nb11 / ggml_type_size(src1->type);
  9107. pc.nb12 = nb12 / ggml_type_size(src1->type);
  9108. pc.nb13 = nb13 / ggml_type_size(src1->type);
  9109. pc.s0 = s0;
  9110. pc.s1 = s1;
  9111. pc.s2 = s2;
  9112. pc.p0 = p0;
  9113. pc.p1 = p1;
  9114. pc.p2 = p2;
  9115. pc.d0 = d0;
  9116. pc.d1 = d1;
  9117. pc.d2 = d2;
  9118. pc.IW = IW;
  9119. pc.IH = IH;
  9120. pc.ID = ID;
  9121. pc.IC = IC;
  9122. pc.KW = KW;
  9123. pc.OH = OH;
  9124. pc.KD_KH_KW = KD*KH*KW;
  9125. pc.KH_KW = KH*KW;
  9126. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  9127. pc.N_OD_OH = N*OD*OH;
  9128. pc.OD_OH = OD*OH;
  9129. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  9130. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  9131. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  9132. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  9133. }
  9134. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9135. const uint32_t dim = dst->op_params[0];
  9136. const uint32_t max_period = dst->op_params[1];
  9137. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  9138. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  9139. nb1, dim, max_period,
  9140. });
  9141. }
  9142. static void ggml_vk_conv_transpose_1d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9143. // src0: (K, Cout, Cin, 1) -- kernel
  9144. // src1: (L, Cin, 1, 1) -- input
  9145. // dst: (*, Cout, 1, 1)
  9146. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  9147. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9148. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  9149. GGML_TENSOR_BINARY_OP_LOCALS
  9150. GGML_ASSERT(nb00 == sizeof(float));
  9151. GGML_ASSERT(nb10 == sizeof(float));
  9152. const int32_t s0 = dst->op_params[0];
  9153. vk_op_conv_transpose_1d_push_constants p{};
  9154. p.Cout = static_cast<uint32_t>(ne01);
  9155. p.Cin = static_cast<uint32_t>(ne02);
  9156. p.K = static_cast<uint32_t>(ne00);
  9157. p.L = static_cast<uint32_t>(ne10);
  9158. p.KL = static_cast<uint32_t>(ne0);
  9159. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9160. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9161. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9162. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9163. p.s0 = static_cast<uint32_t>(s0);
  9164. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  9165. }
  9166. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9167. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  9168. const int32_t k1 = dst->op_params[1];
  9169. const int32_t k0 = dst->op_params[2];
  9170. const int32_t s1 = dst->op_params[3];
  9171. const int32_t s0 = dst->op_params[4];
  9172. const int32_t p1 = dst->op_params[5];
  9173. const int32_t p0 = dst->op_params[6];
  9174. const uint32_t IH = src0->ne[1];
  9175. const uint32_t IW = src0->ne[0];
  9176. const uint32_t N = dst->ne[3];
  9177. const uint32_t OC = dst->ne[2];
  9178. const uint32_t OH = dst->ne[1];
  9179. const uint32_t OW = dst->ne[0];
  9180. const uint32_t parallel_elements = N * OC * OH * OW;
  9181. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  9182. IW, IH, OW, OH, OC,
  9183. parallel_elements,
  9184. op,
  9185. k0, k1, s0, s1, p0, p1,
  9186. });
  9187. }
  9188. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  9189. const ggml_tensor * src1, ggml_tensor * dst) {
  9190. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  9191. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9192. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  9193. GGML_TENSOR_BINARY_OP_LOCALS
  9194. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  9195. GGML_ASSERT(nb10 == sizeof(float));
  9196. GGML_ASSERT(nb0 == sizeof(float));
  9197. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  9198. vk_op_conv2d_push_constants p{};
  9199. p.Cout = static_cast<uint32_t>(!transpose ? ne03 : ne02);
  9200. p.Cin = static_cast<uint32_t>(!transpose ? ne02 : ne03);
  9201. p.N = static_cast<uint32_t>(ne13);
  9202. GGML_ASSERT(p.Cout == ne2);
  9203. GGML_ASSERT(p.Cin == ne12);
  9204. p.W = static_cast<uint32_t>(ne10);
  9205. p.H = static_cast<uint32_t>(ne11);
  9206. p.OW = static_cast<uint32_t>(ne0);
  9207. p.OH = static_cast<uint32_t>(ne1);
  9208. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9209. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9210. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  9211. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9212. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  9213. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  9214. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9215. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  9216. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  9217. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, dst->op, std::move(p));
  9218. }
  9219. static void ggml_vk_conv_2d_dw(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9220. vk_op_conv2d_dw_push_constants p{};
  9221. p.ne = ggml_nelements(dst);
  9222. p.channels = dst->ne[2];
  9223. p.batches = dst->ne[3];
  9224. p.dst_w = dst->ne[0];
  9225. p.dst_h = dst->ne[1];
  9226. p.src_w = src1->ne[0];
  9227. p.src_h = src1->ne[1];
  9228. p.knl_w = src0->ne[0];
  9229. p.knl_h = src0->ne[1];
  9230. p.stride_x = dst->op_params[0];
  9231. p.stride_y = dst->op_params[1];
  9232. p.pad_x = dst->op_params[2];
  9233. p.pad_y = dst->op_params[3];
  9234. p.dilation_x = dst->op_params[4];
  9235. p.dilation_y = dst->op_params[5];
  9236. GGML_ASSERT(src0->ne[3] == p.channels);
  9237. GGML_ASSERT(src1->ne[3] == p.batches);
  9238. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  9239. }
  9240. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9241. const float * op_params = (const float *)dst->op_params;
  9242. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f });
  9243. }
  9244. #ifdef GGML_VULKAN_RUN_TESTS
  9245. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  9246. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  9247. return;
  9248. }
  9249. i0 = std::max(i0, 5);
  9250. i1 = std::max(i1, 5);
  9251. i2 = std::max(i2, 0);
  9252. fprintf(stderr, " ");
  9253. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9254. fprintf(stderr, "%7d ", idx1);
  9255. }
  9256. fprintf(stderr, "\n");
  9257. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9258. fprintf(stderr, "%7d: ", idx0);
  9259. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9260. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  9261. float val;
  9262. if (type == GGML_TYPE_F32) {
  9263. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  9264. } else if (type == GGML_TYPE_F16) {
  9265. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  9266. } else {
  9267. GGML_ABORT("fatal error");
  9268. }
  9269. fprintf(stderr, "% 7.2f ", val);
  9270. } else {
  9271. fprintf(stderr, " ");
  9272. }
  9273. }
  9274. fprintf(stderr, "\n");
  9275. }
  9276. }
  9277. template <typename X_TYPE, typename Y_TYPE>
  9278. 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) {
  9279. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  9280. const size_t x_ne = m * k * batch;
  9281. const size_t y_ne = k * n * batch;
  9282. const size_t d_ne = m * n * batch;
  9283. vk_pipeline p;
  9284. std::string shname;
  9285. if (shader_size == 0) {
  9286. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9287. p = ctx->device->pipeline_matmul_f32->a_s;
  9288. shname = "F32_ALIGNED_S";
  9289. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9290. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  9291. shname = "F32_F16_ALIGNED_S";
  9292. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9293. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  9294. shname = "F16_F32_ALIGNED_S";
  9295. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9296. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  9297. shname = "F16_ALIGNED_S";
  9298. } else {
  9299. GGML_ABORT("fatal error");
  9300. }
  9301. } else if (shader_size == 1) {
  9302. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9303. p = ctx->device->pipeline_matmul_f32->a_m;
  9304. shname = "F32_ALIGNED_M";
  9305. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9306. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  9307. shname = "F32_F16_ALIGNED_M";
  9308. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9309. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  9310. shname = "F16_F32_ALIGNED_M";
  9311. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9312. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  9313. shname = "F16_ALIGNED_M";
  9314. } else {
  9315. GGML_ABORT("fatal error");
  9316. }
  9317. } else if (shader_size == 2) {
  9318. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9319. p = ctx->device->pipeline_matmul_f32->a_l;
  9320. shname = "F32_ALIGNED_L";
  9321. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9322. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  9323. shname = "F32_F16_ALIGNED_L";
  9324. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9325. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  9326. shname = "F16_F32_ALIGNED_L";
  9327. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9328. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  9329. shname = "F16_ALIGNED_L";
  9330. } else {
  9331. GGML_ABORT("fatal error");
  9332. }
  9333. } else {
  9334. GGML_ASSERT(0);
  9335. }
  9336. const size_t kpad = ggml_vk_align_size(k, p->align);
  9337. if (k != kpad) {
  9338. if (shader_size == 0) {
  9339. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9340. p = ctx->device->pipeline_matmul_f32->s;
  9341. shname = "F32_S";
  9342. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9343. p = ctx->device->pipeline_matmul_f32_f16->s;
  9344. shname = "F32_F16_S";
  9345. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9346. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  9347. shname = "F16_F32_S";
  9348. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9349. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  9350. shname = "F16_S";
  9351. }
  9352. } else if (shader_size == 1) {
  9353. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9354. p = ctx->device->pipeline_matmul_f32->m;
  9355. shname = "F32_M";
  9356. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9357. p = ctx->device->pipeline_matmul_f32_f16->m;
  9358. shname = "F32_F16_M";
  9359. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9360. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  9361. shname = "F16_F32_M";
  9362. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9363. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  9364. shname = "F16_M";
  9365. }
  9366. } else if (shader_size == 2) {
  9367. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9368. p = ctx->device->pipeline_matmul_f32->l;
  9369. shname = "F32_L";
  9370. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9371. p = ctx->device->pipeline_matmul_f32_f16->l;
  9372. shname = "F32_F16_L";
  9373. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9374. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  9375. shname = "F16_F32_L";
  9376. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9377. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  9378. shname = "F16_L";
  9379. }
  9380. }
  9381. }
  9382. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9383. if (split_k > 1) {
  9384. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9385. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9386. // Resize buffer
  9387. if (ctx->prealloc_split_k != nullptr) {
  9388. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9389. }
  9390. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9391. }
  9392. }
  9393. ggml_pipeline_allocate_descriptor_sets(ctx);
  9394. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9395. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9396. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9397. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9398. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9399. float* d = (float *) malloc(sizeof(float) * d_ne);
  9400. for (size_t i = 0; i < x_ne; i++) {
  9401. if (std::is_same<float, X_TYPE>()) {
  9402. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9403. // x[i] = 1.0f;
  9404. // x[i] = i + 1;
  9405. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9406. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9407. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9408. // x[i] = ggml_fp32_to_fp16(1.0f);
  9409. // x[i] = ggml_fp32_to_fp16(i + 1);
  9410. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9411. } else {
  9412. GGML_ABORT("fatal error");
  9413. }
  9414. }
  9415. for (size_t i = 0; i < y_ne; i++) {
  9416. if (std::is_same<float, Y_TYPE>()) {
  9417. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9418. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9419. // y[i] = i + 1;
  9420. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9421. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9422. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9423. // y[i] = ggml_fp32_to_fp16(i + 1);
  9424. } else {
  9425. GGML_ABORT("fatal error");
  9426. }
  9427. }
  9428. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9429. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9430. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9431. ggml_vk_ctx_begin(ctx->device, subctx);
  9432. for (size_t i = 0; i < num_it; i++) {
  9433. ggml_vk_matmul(
  9434. ctx, subctx, p, ggml_vk_subbuffer(ctx, d_X), ggml_vk_subbuffer(ctx, d_Y), ggml_vk_subbuffer(ctx, d_D), ggml_vk_subbuffer(ctx, ctx->prealloc_split_k),
  9435. m, n, k,
  9436. k, k, m, k*m, k*n, m*n,
  9437. split_k, batch, batch, batch, 1, 1, n
  9438. );
  9439. }
  9440. ggml_vk_ctx_end(subctx);
  9441. auto begin = std::chrono::high_resolution_clock::now();
  9442. ggml_vk_submit(subctx, ctx->fence);
  9443. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9444. ctx->device->device.resetFences({ ctx->fence });
  9445. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9446. auto end = std::chrono::high_resolution_clock::now();
  9447. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9448. // copy dst to host
  9449. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9450. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9451. ggml_init_params iparams = {
  9452. /*.mem_size =*/ 1024*1024*1024,
  9453. /*.mem_buffer =*/ NULL,
  9454. /*.no_alloc =*/ true,
  9455. };
  9456. ggml_context * ggml_ctx = ggml_init(iparams);
  9457. ggml_type src0_type;
  9458. ggml_type src1_type;
  9459. if (std::is_same<float, X_TYPE>()) {
  9460. src0_type = GGML_TYPE_F32;
  9461. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9462. src0_type = GGML_TYPE_F16;
  9463. } else {
  9464. GGML_ABORT("fatal error");
  9465. }
  9466. if (std::is_same<float, Y_TYPE>()) {
  9467. src1_type = GGML_TYPE_F32;
  9468. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9469. src1_type = GGML_TYPE_F16;
  9470. } else {
  9471. GGML_ABORT("fatal error");
  9472. }
  9473. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9474. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9475. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9476. src0_ggml->data = x;
  9477. src1_ggml->data = y;
  9478. tensor_ggml->data = d_chk;
  9479. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9480. ggml_build_forward_expand(cgraph, tensor_ggml);
  9481. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9482. ggml_free(ggml_ctx);
  9483. double avg_err = 0.0;
  9484. int first_err_n = -1;
  9485. int first_err_m = -1;
  9486. int first_err_b = -1;
  9487. for (size_t i = 0; i < m*n*batch; i++) {
  9488. double err = std::fabs(d[i] - d_chk[i]);
  9489. avg_err += err;
  9490. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9491. first_err_b = i / (m * n);
  9492. first_err_n = (i % (m * n)) / m;
  9493. first_err_m = (i % (m * n)) % m;
  9494. }
  9495. }
  9496. avg_err /= m * n;
  9497. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9498. 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;
  9499. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9500. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9501. std::cerr << "Actual result: " << std::endl << std::endl;
  9502. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9503. std::cerr << "Expected result: " << std::endl << std::endl;
  9504. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9505. if (split_k > 1) {
  9506. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9507. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9508. std::cerr << "d_buf0: " << std::endl << std::endl;
  9509. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9510. std::cerr << "d_buf1: " << std::endl << std::endl;
  9511. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9512. std::cerr << "d_buf2: " << std::endl << std::endl;
  9513. 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);
  9514. std::cerr << "d_buf3: " << std::endl << std::endl;
  9515. 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);
  9516. free(split_k_buf);
  9517. }
  9518. }
  9519. free(d_chk);
  9520. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9521. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9522. ggml_vk_destroy_buffer(d_X);
  9523. ggml_vk_destroy_buffer(d_Y);
  9524. ggml_vk_destroy_buffer(d_D);
  9525. free(x);
  9526. free(y);
  9527. free(d);
  9528. }
  9529. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9530. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9531. return;
  9532. }
  9533. i0 = std::max(i0, 5);
  9534. i1 = std::max(i1, 5);
  9535. i2 = std::max(i2, 0);
  9536. i3 = std::max(i3, 0);
  9537. fprintf(stderr, " ");
  9538. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9539. fprintf(stderr, "%7d ", idx1);
  9540. }
  9541. fprintf(stderr, "\n");
  9542. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9543. fprintf(stderr, "%7d: ", idx0);
  9544. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9545. 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]) {
  9546. float val;
  9547. if (tensor->type == GGML_TYPE_F32) {
  9548. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9549. } else if (tensor->type == GGML_TYPE_F16) {
  9550. 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]));
  9551. } else {
  9552. GGML_ABORT("fatal error");
  9553. }
  9554. fprintf(stderr, "% 7.2f ", val);
  9555. } else {
  9556. fprintf(stderr, " ");
  9557. }
  9558. }
  9559. fprintf(stderr, "\n");
  9560. }
  9561. }
  9562. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9563. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9564. }
  9565. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9566. if (quant == GGML_TYPE_F32) {
  9567. memcpy(to, from, sizeof(float) * ne);
  9568. return;
  9569. }
  9570. const auto * tt = ggml_get_type_traits(quant);
  9571. ggml_to_float_t dequant_fn = tt->to_float;
  9572. dequant_fn(from, to, ne);
  9573. }
  9574. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9575. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9576. const size_t x_sz = sizeof(float) * ne;
  9577. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9578. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9579. float * x = (float *) malloc(x_sz);
  9580. void * qx = malloc(qx_sz);
  9581. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9582. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9583. float * x_ref = (float *) malloc(x_sz);
  9584. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9585. for (size_t i = 0; i < ne; i++) {
  9586. x[i] = rand() / (float)RAND_MAX;
  9587. }
  9588. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9589. ggml_vk_quantize_data(x, qx, ne, quant);
  9590. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9591. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9592. ggml_pipeline_allocate_descriptor_sets(ctx);
  9593. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9594. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9595. ggml_vk_ctx_begin(ctx->device, subctx);
  9596. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9597. ggml_vk_dispatch_pipeline(ctx, subctx, p, { vk_subbuffer{ qx_buf, 0, qx_sz }, vk_subbuffer{ x_buf, 0, x_sz_f16 } }, pc, { (uint32_t)ne, 1, 1});
  9598. ggml_vk_ctx_end(subctx);
  9599. auto begin = std::chrono::high_resolution_clock::now();
  9600. ggml_vk_submit(subctx, ctx->fence);
  9601. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9602. ctx->device->device.resetFences({ ctx->fence });
  9603. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9604. auto end = std::chrono::high_resolution_clock::now();
  9605. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9606. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9607. int first_err = -1;
  9608. double avg_err = 0.0;
  9609. for (size_t i = 0; i < ne; i++) {
  9610. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9611. avg_err += error;
  9612. if (first_err < 0 && error > 0.05) {
  9613. first_err = i;
  9614. }
  9615. }
  9616. avg_err /= ne;
  9617. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9618. if (avg_err > 0.1) {
  9619. std::cerr << "first_error = " << first_err << std::endl;
  9620. std::cerr << "Actual result: " << std::endl << std::endl;
  9621. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9622. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9623. }
  9624. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9625. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9626. std::cerr << x_ref[i] << ", ";
  9627. }
  9628. std::cerr << std::endl;
  9629. }
  9630. ggml_vk_destroy_buffer(x_buf);
  9631. ggml_vk_destroy_buffer(qx_buf);
  9632. free(x);
  9633. free(qx);
  9634. free(x_ref);
  9635. free(x_chk);
  9636. }
  9637. // This does not work without ggml q8_1 quantization support
  9638. //
  9639. // typedef uint16_t ggml_half;
  9640. // typedef uint32_t ggml_half2;
  9641. //
  9642. // #define QK8_1 32
  9643. // typedef struct {
  9644. // union {
  9645. // struct {
  9646. // ggml_half d; // delta
  9647. // ggml_half s; // d * sum(qs[i])
  9648. // } GGML_COMMON_AGGR_S;
  9649. // ggml_half2 ds;
  9650. // } GGML_COMMON_AGGR_U;
  9651. // int8_t qs[QK8_1]; // quants
  9652. // } block_q8_1;
  9653. //
  9654. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9655. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9656. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9657. //
  9658. // const size_t x_sz = sizeof(float) * ne;
  9659. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9660. // float * x = (float *) malloc(x_sz);
  9661. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9662. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9663. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9664. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9665. //
  9666. // for (size_t i = 0; i < ne; i++) {
  9667. // x[i] = rand() / (float)RAND_MAX;
  9668. // }
  9669. //
  9670. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9671. //
  9672. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9673. //
  9674. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9675. //
  9676. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9677. //
  9678. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9679. // ggml_vk_ctx_begin(ctx->device, subctx);
  9680. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9681. // ggml_vk_ctx_end(subctx);
  9682. //
  9683. // auto begin = std::chrono::high_resolution_clock::now();
  9684. //
  9685. // ggml_vk_submit(subctx, ctx->fence);
  9686. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9687. // ctx->device->device.resetFences({ ctx->fence });
  9688. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9689. //
  9690. // auto end = std::chrono::high_resolution_clock::now();
  9691. //
  9692. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9693. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9694. //
  9695. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9696. //
  9697. // int first_err = -1;
  9698. //
  9699. // for (size_t i = 0; i < ne / 32; i++) {
  9700. // double error = std::fabs(ggml_fp16_to_fp32(qx_res[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) - ggml_fp16_to_fp32(qx[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d));
  9701. //
  9702. // if (first_err < 0 && error > 0.1) {
  9703. // first_err = i;
  9704. // }
  9705. //
  9706. // error = std::fabs(ggml_fp16_to_fp32(qx_res[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) - ggml_fp16_to_fp32(qx[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s));
  9707. //
  9708. // if (first_err < 0 && error > 0.1) {
  9709. // first_err = i;
  9710. // }
  9711. //
  9712. // for (size_t j = 0; j < 32; j++) {
  9713. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9714. //
  9715. // if (first_err < 0 && error > 1) {
  9716. // first_err = i;
  9717. // }
  9718. // }
  9719. // }
  9720. //
  9721. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9722. //
  9723. // if (first_err != -1) {
  9724. // std::cerr << "first_error = " << first_err << std::endl;
  9725. // std::cerr << "Actual result: " << std::endl << std::endl;
  9726. // std::cout << "d=" << ggml_fp16_to_fp32(qx[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) << " s=" << ggml_fp16_to_fp32(qx[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) << " ";
  9727. // for (size_t j = 0; j < 32; j++) {
  9728. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9729. // }
  9730. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9731. // std::cout << "d=" << ggml_fp16_to_fp32(qx_res[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) << " s=" << ggml_fp16_to_fp32(qx_res[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) << " ";
  9732. // for (size_t j = 0; j < 32; j++) {
  9733. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9734. // }
  9735. // std::cerr << std::endl;
  9736. // }
  9737. //
  9738. // ggml_vk_destroy_buffer(x_buf);
  9739. // ggml_vk_destroy_buffer(qx_buf);
  9740. //
  9741. // free(x);
  9742. // free(qx);
  9743. // free(qx_res);
  9744. // }
  9745. static void ggml_vk_test_dequant_matmul(ggml_backend_vk_context * ctx, size_t m, size_t n, size_t k, size_t batch, size_t num_it, size_t split_k, size_t shader_size, ggml_type quant, bool mmq = false) {
  9746. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9747. const size_t x_ne = m * k * batch;
  9748. const size_t y_ne = k * n * batch;
  9749. const size_t d_ne = m * n * batch;
  9750. vk_matmul_pipeline2 * pipelines;
  9751. if (mmq) {
  9752. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9753. } else {
  9754. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9755. }
  9756. const bool fp16acc = ctx->device->fp16;
  9757. vk_pipeline p;
  9758. std::string shname;
  9759. if (shader_size == 0) {
  9760. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9761. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9762. } else if (shader_size == 1) {
  9763. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9764. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9765. } else if (shader_size == 2) {
  9766. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9767. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9768. } else {
  9769. GGML_ASSERT(0);
  9770. }
  9771. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9772. if (mmq || k != kpad) {
  9773. if (shader_size == 0) {
  9774. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9775. shname = std::string(ggml_type_name(quant)) + "_S";
  9776. } else if (shader_size == 1) {
  9777. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9778. shname = std::string(ggml_type_name(quant)) + "_M";
  9779. } else if (shader_size == 2) {
  9780. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9781. shname = std::string(ggml_type_name(quant)) + "_L";
  9782. } else {
  9783. GGML_ASSERT(0);
  9784. }
  9785. }
  9786. if (p == nullptr) {
  9787. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9788. return;
  9789. }
  9790. const size_t x_sz = sizeof(float) * x_ne;
  9791. const size_t y_sz = sizeof(float) * y_ne;
  9792. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9793. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9794. const size_t d_sz = sizeof(float) * d_ne;
  9795. float * x = (float *) malloc(x_sz);
  9796. float * y = (float *) malloc(y_sz);
  9797. void * qx = malloc(qx_sz);
  9798. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9799. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9800. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9801. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9802. float * d = (float *) malloc(d_sz);
  9803. float * d_chk = (float *) malloc(d_sz);
  9804. for (size_t i = 0; i < x_ne; i++) {
  9805. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9806. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9807. // x[i] = i % k;
  9808. }
  9809. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9810. for (size_t i = 0; i < y_ne; i++) {
  9811. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9812. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9813. // y[i] = i % k;
  9814. }
  9815. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9816. if (split_k > 1) {
  9817. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9818. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9819. // Resize buffer
  9820. if (ctx->prealloc_split_k != nullptr) {
  9821. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9822. }
  9823. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9824. }
  9825. }
  9826. if (mmq) {
  9827. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9828. }
  9829. ggml_pipeline_allocate_descriptor_sets(ctx);
  9830. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9831. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9832. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9833. ggml_vk_ctx_begin(ctx->device, subctx);
  9834. if (mmq) {
  9835. for (size_t i = 0; i < num_it; i++) {
  9836. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9837. ggml_vk_matmul(
  9838. ctx, subctx, p, { qx_buf, 0, qx_sz }, { qy_buf, 0, qy_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k },
  9839. m, n, k,
  9840. k, k, m, k*m, k*n, m*n,
  9841. split_k, batch, batch, batch, 1, 1, n
  9842. );
  9843. }
  9844. } else {
  9845. for (size_t i = 0; i < num_it; i++) {
  9846. ggml_vk_matmul(
  9847. ctx, subctx, p, { qx_buf, 0, qx_sz }, { y_buf, 0, y_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k },
  9848. m, n, k,
  9849. k, k, m, k*m, k*n, m*n,
  9850. split_k, batch, batch, batch, 1, 1, n
  9851. );
  9852. }
  9853. }
  9854. ggml_vk_ctx_end(subctx);
  9855. auto begin = std::chrono::high_resolution_clock::now();
  9856. ggml_vk_submit(subctx, ctx->fence);
  9857. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9858. ctx->device->device.resetFences({ ctx->fence });
  9859. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9860. auto end = std::chrono::high_resolution_clock::now();
  9861. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9862. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9863. ggml_init_params iparams = {
  9864. /*.mem_size =*/ 1024*1024*1024,
  9865. /*.mem_buffer =*/ NULL,
  9866. /*.no_alloc =*/ true,
  9867. };
  9868. ggml_context * ggml_ctx = ggml_init(iparams);
  9869. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9870. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9871. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9872. src0_ggml->data = qx;
  9873. src1_ggml->data = y;
  9874. tensor_ggml->data = d_chk;
  9875. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9876. ggml_build_forward_expand(cgraph, tensor_ggml);
  9877. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9878. ggml_free(ggml_ctx);
  9879. double avg_err = 0.0;
  9880. int first_err_n = -1;
  9881. int first_err_m = -1;
  9882. int first_err_b = -1;
  9883. for (size_t i = 0; i < m*n*batch; i++) {
  9884. double err = std::fabs(d[i] - d_chk[i]);
  9885. avg_err += err;
  9886. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9887. first_err_b = i / (m * n);
  9888. first_err_n = (i % (m * n)) / m;
  9889. first_err_m = (i % (m * n)) % m;
  9890. }
  9891. }
  9892. avg_err /= m * n;
  9893. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9894. std::cerr << "TEST dequant matmul " << shname;
  9895. if (mmq) {
  9896. std::cerr << " mmq";
  9897. }
  9898. std::cerr << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time_ms / num_it << "ms " << tflops << " TFLOPS avg_err=" << avg_err << std::endl;
  9899. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9900. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9901. std::cerr << "Actual result: " << std::endl << std::endl;
  9902. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9903. std::cerr << std::endl;
  9904. std::cerr << "Expected result: " << std::endl << std::endl;
  9905. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9906. std::cerr << "src0: " << std::endl << std::endl;
  9907. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9908. std::cerr << std::endl;
  9909. std::cerr << "src1: " << std::endl << std::endl;
  9910. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9911. if (split_k > 1) {
  9912. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9913. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9914. std::cerr << "d_buf0: " << std::endl << std::endl;
  9915. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9916. std::cerr << "d_buf1: " << std::endl << std::endl;
  9917. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9918. std::cerr << "d_buf2: " << std::endl << std::endl;
  9919. 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);
  9920. std::cerr << "d_buf3: " << std::endl << std::endl;
  9921. 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);
  9922. free(split_k_buf);
  9923. }
  9924. }
  9925. ggml_vk_destroy_buffer(qx_buf);
  9926. ggml_vk_destroy_buffer(y_buf);
  9927. ggml_vk_destroy_buffer(qy_buf);
  9928. ggml_vk_destroy_buffer(d_buf);
  9929. free(x);
  9930. free(qx);
  9931. free(y);
  9932. free(d);
  9933. free(d_chk);
  9934. }
  9935. #endif
  9936. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  9937. #if defined(GGML_VULKAN_RUN_TESTS)
  9938. const std::vector<size_t> vals {
  9939. 512, 512, 128,
  9940. 128, 512, 512,
  9941. 4096, 512, 4096,
  9942. 11008, 512, 4096,
  9943. 4096, 512, 11008,
  9944. 32000, 512, 4096,
  9945. 8, 8, 8,
  9946. 100, 46, 576,
  9947. 623, 111, 128,
  9948. 100, 46, 558,
  9949. 512, 1, 256,
  9950. 128, 110, 622,
  9951. 511, 511, 127,
  9952. 511, 511, 7,
  9953. 511, 511, 17,
  9954. 49, 49, 128,
  9955. 128, 49, 49,
  9956. 4096, 49, 4096,
  9957. };
  9958. const size_t num_it = 100;
  9959. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9960. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9961. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9962. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9963. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9964. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9965. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9966. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9967. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9968. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9969. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9970. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9971. abort();
  9972. for (size_t i = 0; i < vals.size(); i += 3) {
  9973. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9974. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9975. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9976. std::cerr << '\n';
  9977. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9978. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9979. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9980. std::cerr << '\n';
  9981. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9982. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9983. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9984. std::cerr << '\n' << std::endl;
  9985. if (vals[i + 2] % 32 == 0) {
  9986. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9987. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9988. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9989. std::cerr << '\n';
  9990. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9991. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9992. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9993. std::cerr << '\n';
  9994. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9995. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9996. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9997. std::cerr << '\n' << std::endl;
  9998. }
  9999. if (vals[i + 2] % 256 == 0) {
  10000. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  10001. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  10002. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  10003. std::cerr << '\n';
  10004. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  10005. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  10006. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  10007. std::cerr << '\n';
  10008. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  10009. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  10010. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  10011. std::cerr << '\n' << std::endl;
  10012. }
  10013. }
  10014. GGML_ABORT("fatal error");
  10015. #endif
  10016. if (subctx) {
  10017. // Submit and wait for any pending work before reallocating the buffers
  10018. ggml_vk_ctx_end(subctx);
  10019. ggml_vk_submit(subctx, {});
  10020. ctx->submit_pending = true;
  10021. ggml_vk_synchronize(ctx);
  10022. ggml_vk_ctx_begin(ctx->device, subctx);
  10023. }
  10024. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  10025. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  10026. // Resize buffer
  10027. if (ctx->prealloc_x != nullptr) {
  10028. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10029. }
  10030. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  10031. }
  10032. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  10033. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  10034. // Resize buffer
  10035. if (ctx->prealloc_y != nullptr) {
  10036. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10037. }
  10038. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  10039. }
  10040. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  10041. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  10042. // Resize buffer
  10043. if (ctx->prealloc_split_k != nullptr) {
  10044. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10045. }
  10046. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  10047. }
  10048. if (ctx->prealloc_add_rms_partials == nullptr || (ctx->prealloc_size_add_rms_partials > 0 && ctx->prealloc_add_rms_partials->size < ctx->prealloc_size_add_rms_partials)) {
  10049. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  10050. // Resize buffer
  10051. if (ctx->prealloc_add_rms_partials != nullptr) {
  10052. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10053. }
  10054. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  10055. }
  10056. }
  10057. static void ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool almost_ready);
  10058. // Returns true if node has enqueued work into the queue, false otherwise
  10059. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  10060. static bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool last_node, bool almost_ready, bool submit){
  10061. ggml_tensor * node = cgraph->nodes[node_idx];
  10062. if (ggml_is_empty(node) || ggml_op_is_empty(node->op) || !node->buffer) {
  10063. return false;
  10064. }
  10065. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  10066. ctx->semaphore_idx = 0;
  10067. ggml_tensor * src0 = node->src[0];
  10068. ggml_tensor * src1 = node->src[1];
  10069. ggml_tensor * src2 = node->src[2];
  10070. ggml_tensor * src3 = node->src[3];
  10071. if (node->op == GGML_OP_ADD) {
  10072. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  10073. if (next_node_idx < cgraph->n_nodes &&
  10074. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  10075. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  10076. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  10077. ctx->device->add_rms_fusion) {
  10078. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  10079. ctx->do_add_rms_partials_offset_calculation = true;
  10080. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  10081. ctx->do_add_rms_partials = true;
  10082. }
  10083. }
  10084. }
  10085. vk_context compute_ctx;
  10086. if (ctx->compute_ctx.expired()) {
  10087. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10088. ctx->compute_ctx = compute_ctx;
  10089. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10090. } else {
  10091. compute_ctx = ctx->compute_ctx.lock();
  10092. }
  10093. {
  10094. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  10095. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  10096. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  10097. // outside of this logic. When a node uses one of the prealloc buffers for something like
  10098. // dequantization or split_k, additional synchronization is needed between those passes.
  10099. bool need_sync = false;
  10100. // Check whether "node" requires synchronization. The node requires synchronization if it
  10101. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  10102. // Destination nodes are checked against both the written/read lists. Source nodes are only
  10103. // checked against the written list. Two nodes overlap in memory if they come from the same
  10104. // buffer and the tensor or view ranges overlap.
  10105. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  10106. if (unsynced_nodes.size() == 0) {
  10107. return false;
  10108. }
  10109. auto n_base = vk_tensor_offset(node) + node->view_offs;
  10110. auto n_size = ggml_nbytes(node);
  10111. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  10112. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10113. for (auto &other : unsynced_nodes) {
  10114. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  10115. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  10116. if (a_buf == o_buf) {
  10117. auto o_base = vk_tensor_offset(other) + other->view_offs;
  10118. auto o_size = ggml_nbytes(other);
  10119. if ((o_base <= n_base && n_base < o_base + o_size) ||
  10120. (n_base <= o_base && o_base < n_base + n_size)) {
  10121. return true;
  10122. }
  10123. }
  10124. }
  10125. return false;
  10126. };
  10127. // For all fused ops, check if the destination node or any of the source
  10128. // nodes require synchronization.
  10129. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  10130. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10131. // If the node actually writes to memory, then check if it needs to sync
  10132. if (ctx->fused_ops_write_mask & (1 << i)) {
  10133. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  10134. need_sync = true;
  10135. break;
  10136. }
  10137. }
  10138. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10139. if (!cur_node->src[j]) {
  10140. continue;
  10141. }
  10142. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  10143. need_sync = true;
  10144. break;
  10145. }
  10146. }
  10147. }
  10148. #define ENABLE_SYNC_LOGGING 0
  10149. if (need_sync) {
  10150. #if ENABLE_SYNC_LOGGING
  10151. std::cerr << "sync" << std::endl;
  10152. #endif
  10153. ctx->unsynced_nodes_written.clear();
  10154. ctx->unsynced_nodes_read.clear();
  10155. ggml_vk_sync_buffers(ctx, compute_ctx);
  10156. }
  10157. // Add all fused nodes to the unsynchronized lists.
  10158. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10159. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10160. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  10161. if (ctx->fused_ops_write_mask & (1 << i)) {
  10162. ctx->unsynced_nodes_written.push_back(cur_node);
  10163. }
  10164. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10165. if (!cur_node->src[j]) {
  10166. continue;
  10167. }
  10168. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  10169. }
  10170. }
  10171. }
  10172. #if ENABLE_SYNC_LOGGING
  10173. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10174. auto *n = cgraph->nodes[node_idx + i];
  10175. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  10176. if (n->op == GGML_OP_GLU) {
  10177. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  10178. }
  10179. if (n->op == GGML_OP_ROPE) {
  10180. const int mode = ((const int32_t *) n->op_params)[2];
  10181. std::cerr << " rope mode: " << mode;
  10182. }
  10183. std::cerr << std::endl;
  10184. }
  10185. #endif
  10186. switch (node->op) {
  10187. case GGML_OP_REPEAT:
  10188. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  10189. break;
  10190. case GGML_OP_REPEAT_BACK:
  10191. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  10192. break;
  10193. case GGML_OP_ACC:
  10194. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  10195. break;
  10196. case GGML_OP_GET_ROWS:
  10197. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  10198. break;
  10199. case GGML_OP_ADD:
  10200. if (ctx->num_additional_fused_ops) {
  10201. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  10202. } else {
  10203. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  10204. }
  10205. break;
  10206. case GGML_OP_SUB:
  10207. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  10208. break;
  10209. case GGML_OP_MUL:
  10210. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  10211. break;
  10212. case GGML_OP_DIV:
  10213. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  10214. break;
  10215. case GGML_OP_ADD_ID:
  10216. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  10217. break;
  10218. case GGML_OP_CONCAT:
  10219. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  10220. break;
  10221. case GGML_OP_UPSCALE:
  10222. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  10223. break;
  10224. case GGML_OP_ADD1:
  10225. ggml_vk_add1(ctx, compute_ctx, src0, src1, node);
  10226. break;
  10227. case GGML_OP_ARANGE:
  10228. ggml_vk_arange(ctx, compute_ctx, node);
  10229. break;
  10230. case GGML_OP_FILL:
  10231. ggml_vk_fill(ctx, compute_ctx, node);
  10232. break;
  10233. case GGML_OP_SCALE:
  10234. ggml_vk_scale(ctx, compute_ctx, src0, node);
  10235. break;
  10236. case GGML_OP_SQR:
  10237. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  10238. break;
  10239. case GGML_OP_SQRT:
  10240. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  10241. break;
  10242. case GGML_OP_SIN:
  10243. ggml_vk_sin(ctx, compute_ctx, src0, node);
  10244. break;
  10245. case GGML_OP_COS:
  10246. ggml_vk_cos(ctx, compute_ctx, src0, node);
  10247. break;
  10248. case GGML_OP_LOG:
  10249. ggml_vk_log(ctx, compute_ctx, src0, node);
  10250. break;
  10251. case GGML_OP_TRI:
  10252. ggml_vk_tri(ctx, compute_ctx, src0, node);
  10253. break;
  10254. case GGML_OP_DIAG:
  10255. ggml_vk_diag(ctx, compute_ctx, src0, node);
  10256. break;
  10257. case GGML_OP_CLAMP:
  10258. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  10259. break;
  10260. case GGML_OP_PAD:
  10261. ggml_vk_pad(ctx, compute_ctx, src0, node);
  10262. break;
  10263. case GGML_OP_ROLL:
  10264. ggml_vk_roll(ctx, compute_ctx, src0, node);
  10265. break;
  10266. case GGML_OP_CPY:
  10267. case GGML_OP_CONT:
  10268. case GGML_OP_DUP:
  10269. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  10270. break;
  10271. case GGML_OP_SET_ROWS:
  10272. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  10273. break;
  10274. case GGML_OP_SILU_BACK:
  10275. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  10276. break;
  10277. case GGML_OP_NORM:
  10278. ggml_vk_norm(ctx, compute_ctx, src0, node);
  10279. break;
  10280. case GGML_OP_GROUP_NORM:
  10281. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  10282. break;
  10283. case GGML_OP_RMS_NORM:
  10284. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  10285. break;
  10286. case GGML_OP_RMS_NORM_BACK:
  10287. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  10288. break;
  10289. case GGML_OP_L2_NORM:
  10290. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  10291. break;
  10292. case GGML_OP_UNARY:
  10293. switch (ggml_get_unary_op(node)) {
  10294. case GGML_UNARY_OP_EXP:
  10295. case GGML_UNARY_OP_SILU:
  10296. case GGML_UNARY_OP_GELU:
  10297. case GGML_UNARY_OP_GELU_ERF:
  10298. case GGML_UNARY_OP_GELU_QUICK:
  10299. case GGML_UNARY_OP_RELU:
  10300. case GGML_UNARY_OP_NEG:
  10301. case GGML_UNARY_OP_TANH:
  10302. case GGML_UNARY_OP_SIGMOID:
  10303. case GGML_UNARY_OP_HARDSIGMOID:
  10304. case GGML_UNARY_OP_HARDSWISH:
  10305. case GGML_UNARY_OP_ABS:
  10306. case GGML_UNARY_OP_SOFTPLUS:
  10307. case GGML_UNARY_OP_STEP:
  10308. case GGML_UNARY_OP_ROUND:
  10309. case GGML_UNARY_OP_CEIL:
  10310. case GGML_UNARY_OP_FLOOR:
  10311. case GGML_UNARY_OP_TRUNC:
  10312. ggml_vk_unary(ctx, compute_ctx, src0, node);
  10313. break;
  10314. default:
  10315. return false;
  10316. }
  10317. break;
  10318. case GGML_OP_GLU:
  10319. switch (ggml_get_glu_op(node)) {
  10320. case GGML_GLU_OP_GEGLU:
  10321. case GGML_GLU_OP_REGLU:
  10322. case GGML_GLU_OP_SWIGLU:
  10323. case GGML_GLU_OP_SWIGLU_OAI:
  10324. case GGML_GLU_OP_GEGLU_ERF:
  10325. case GGML_GLU_OP_GEGLU_QUICK:
  10326. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  10327. break;
  10328. default:
  10329. return false;
  10330. }
  10331. break;
  10332. case GGML_OP_DIAG_MASK_INF:
  10333. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  10334. break;
  10335. case GGML_OP_SOFT_MAX:
  10336. if (ctx->num_additional_fused_ops) {
  10337. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10338. } else {
  10339. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  10340. }
  10341. break;
  10342. case GGML_OP_SOFT_MAX_BACK:
  10343. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  10344. break;
  10345. case GGML_OP_ROPE:
  10346. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  10347. break;
  10348. case GGML_OP_ROPE_BACK:
  10349. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  10350. break;
  10351. case GGML_OP_ARGSORT:
  10352. if (ctx->num_additional_fused_ops) {
  10353. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10354. } else {
  10355. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10356. }
  10357. break;
  10358. case GGML_OP_TOP_K:
  10359. ggml_vk_topk(ctx, compute_ctx, src0, node);
  10360. break;
  10361. case GGML_OP_SUM:
  10362. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10363. break;
  10364. case GGML_OP_SUM_ROWS:
  10365. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10366. break;
  10367. case GGML_OP_CUMSUM:
  10368. ggml_vk_cumsum(ctx, compute_ctx, src0, node);
  10369. break;
  10370. case GGML_OP_MEAN:
  10371. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10372. break;
  10373. case GGML_OP_ARGMAX:
  10374. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10375. break;
  10376. case GGML_OP_COUNT_EQUAL:
  10377. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10378. break;
  10379. case GGML_OP_SOLVE_TRI:
  10380. ggml_vk_solve_tri(ctx, compute_ctx, src0, src1, node);
  10381. break;
  10382. case GGML_OP_IM2COL:
  10383. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10384. break;
  10385. case GGML_OP_IM2COL_3D:
  10386. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10387. break;
  10388. case GGML_OP_TIMESTEP_EMBEDDING:
  10389. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10390. break;
  10391. case GGML_OP_CONV_TRANSPOSE_1D:
  10392. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10393. break;
  10394. case GGML_OP_POOL_2D:
  10395. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10396. break;
  10397. case GGML_OP_CONV_2D:
  10398. case GGML_OP_CONV_TRANSPOSE_2D:
  10399. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10400. break;
  10401. case GGML_OP_CONV_2D_DW:
  10402. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10403. break;
  10404. case GGML_OP_LEAKY_RELU:
  10405. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10406. break;
  10407. case GGML_OP_MUL_MAT:
  10408. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10409. break;
  10410. case GGML_OP_MUL_MAT_ID:
  10411. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10412. break;
  10413. case GGML_OP_FLASH_ATTN_EXT:
  10414. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10415. break;
  10416. case GGML_OP_RWKV_WKV6:
  10417. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10418. break;
  10419. case GGML_OP_RWKV_WKV7:
  10420. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10421. break;
  10422. case GGML_OP_SSM_SCAN:
  10423. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10424. break;
  10425. case GGML_OP_SSM_CONV:
  10426. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10427. break;
  10428. case GGML_OP_OPT_STEP_ADAMW:
  10429. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10430. break;
  10431. case GGML_OP_OPT_STEP_SGD:
  10432. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10433. break;
  10434. default:
  10435. return false;
  10436. }
  10437. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10438. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10439. // Force context reset on each node so that each tensor ends up in its own context
  10440. // and can be run and compared to its CPU equivalent separately
  10441. last_node = true;
  10442. #endif
  10443. if (submit || last_node) {
  10444. ggml_vk_ctx_end(compute_ctx);
  10445. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10446. if (last_node) {
  10447. compute_ctx->exit_tensor_idx = node_idx_begin;
  10448. }
  10449. else {
  10450. compute_ctx->exit_tensor_idx = -1;
  10451. }
  10452. ctx->compute_ctx.reset();
  10453. ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready);
  10454. }
  10455. return true;
  10456. }
  10457. static void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready = false) {
  10458. GGML_UNUSED(cgraph);
  10459. GGML_UNUSED(tensor);
  10460. 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 << ")");
  10461. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10462. // Only run if ctx hasn't been submitted yet
  10463. if (!subctx->seqs.empty()) {
  10464. #ifdef GGML_VULKAN_CHECK_RESULTS
  10465. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10466. #endif
  10467. // Do staging buffer copies
  10468. for (auto& cpy : subctx->in_memcpys) {
  10469. memcpy(cpy.dst, cpy.src, cpy.n);
  10470. }
  10471. for (auto& mset : subctx->memsets) {
  10472. memset(mset.dst, mset.val, mset.n);
  10473. }
  10474. if (almost_ready && !ctx->almost_ready_fence_pending) {
  10475. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10476. ctx->almost_ready_fence_pending = true;
  10477. } else {
  10478. ggml_vk_submit(subctx, {});
  10479. }
  10480. ctx->submit_pending = true;
  10481. #ifdef GGML_VULKAN_CHECK_RESULTS
  10482. ggml_vk_synchronize(ctx);
  10483. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10484. #endif
  10485. }
  10486. if (tensor_idx == subctx->exit_tensor_idx) {
  10487. // Do staging buffer copies
  10488. for (auto& cpy : subctx->out_memcpys) {
  10489. memcpy(cpy.dst, cpy.src, cpy.n);
  10490. }
  10491. subctx->in_memcpys.clear();
  10492. subctx->out_memcpys.clear();
  10493. subctx->memsets.clear();
  10494. }
  10495. }
  10496. // Clean up after graph processing is done
  10497. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10498. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10499. ctx->prealloc_y_last_pipeline_used = {};
  10500. ctx->unsynced_nodes_written.clear();
  10501. ctx->unsynced_nodes_read.clear();
  10502. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10503. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10504. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10505. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10506. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10507. }
  10508. ctx->gc.semaphores.clear();
  10509. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10510. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10511. }
  10512. ctx->gc.tl_semaphores.clear();
  10513. ctx->semaphore_idx = 0;
  10514. ctx->event_idx = 0;
  10515. for (auto& event : ctx->gc.events) {
  10516. ctx->device->device.resetEvent(event);
  10517. }
  10518. ctx->tensor_ctxs.clear();
  10519. ctx->gc.contexts.clear();
  10520. ctx->pipeline_descriptor_set_requirements = 0;
  10521. ctx->descriptor_set_idx = 0;
  10522. }
  10523. // Clean up on backend free
  10524. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10525. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10526. // discard any unsubmitted command buffers
  10527. ctx->transfer_ctx.reset();
  10528. // wait for any pending command buffers to finish
  10529. ggml_vk_synchronize(ctx);
  10530. ggml_vk_graph_cleanup(ctx);
  10531. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10532. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10533. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10534. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10535. ggml_vk_destroy_buffer(ctx->sync_staging);
  10536. ctx->prealloc_y_last_pipeline_used = nullptr;
  10537. ctx->prealloc_size_x = 0;
  10538. ctx->prealloc_size_y = 0;
  10539. ctx->prealloc_size_split_k = 0;
  10540. for (auto& event : ctx->gc.events) {
  10541. ctx->device->device.destroyEvent(event);
  10542. }
  10543. ctx->gc.events.clear();
  10544. ctx->device->device.destroyFence(ctx->fence);
  10545. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10546. for (auto& pool : ctx->descriptor_pools) {
  10547. ctx->device->device.destroyDescriptorPool(pool);
  10548. }
  10549. ctx->descriptor_pools.clear();
  10550. ctx->descriptor_sets.clear();
  10551. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10552. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10553. if (vk_perf_logger_enabled) {
  10554. ctx->perf_logger->print_timings(true);
  10555. }
  10556. }
  10557. static int ggml_vk_get_device_count() {
  10558. ggml_vk_instance_init();
  10559. return vk_instance.device_indices.size();
  10560. }
  10561. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10562. ggml_vk_instance_init();
  10563. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10564. vk::PhysicalDeviceProperties props;
  10565. devices[device].getProperties(&props);
  10566. snprintf(description, description_size, "%s", props.deviceName.data());
  10567. }
  10568. // backend interface
  10569. #define UNUSED GGML_UNUSED
  10570. // device backend
  10571. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10572. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10573. }
  10574. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10575. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10576. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10577. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10578. delete ctx;
  10579. }
  10580. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10581. return vk_ptr_base;
  10582. UNUSED(buffer);
  10583. }
  10584. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10585. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10586. if (tensor->view_src != nullptr) {
  10587. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10588. }
  10589. return GGML_STATUS_SUCCESS;
  10590. }
  10591. static void ggml_backend_vk_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
  10592. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10593. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10594. vk_buffer buf = buf_ctx->dev_buffer;
  10595. uint32_t val32 = (uint32_t)value * 0x01010101;
  10596. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10597. }
  10598. 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) {
  10599. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10600. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10601. vk_buffer buf = buf_ctx->dev_buffer;
  10602. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10603. }
  10604. 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) {
  10605. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10606. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10607. vk_buffer buf = buf_ctx->dev_buffer;
  10608. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10609. }
  10610. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10611. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10612. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10613. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10614. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10615. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10616. 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));
  10617. return true;
  10618. }
  10619. return false;
  10620. UNUSED(buffer);
  10621. }
  10622. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10623. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10624. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10625. }
  10626. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10627. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10628. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10629. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10630. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10631. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10632. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10633. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10634. /* .clear = */ ggml_backend_vk_buffer_clear,
  10635. /* .reset = */ NULL,
  10636. };
  10637. // vk buffer type
  10638. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10639. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10640. return ctx->name.c_str();
  10641. }
  10642. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10643. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10644. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10645. vk_buffer dev_buffer = nullptr;
  10646. try {
  10647. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10648. } catch (const vk::SystemError& e) {
  10649. return nullptr;
  10650. }
  10651. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10652. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10653. }
  10654. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10655. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10656. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10657. }
  10658. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10659. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10660. return ctx->device->suballocation_block_size;
  10661. }
  10662. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10663. return ggml_nbytes(tensor);
  10664. UNUSED(buft);
  10665. }
  10666. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10667. ggml_vk_instance_init();
  10668. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10669. vk_device dev = ggml_vk_get_device(dev_num);
  10670. return &dev->buffer_type;
  10671. }
  10672. // host buffer type
  10673. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10674. return GGML_VK_NAME "_Host";
  10675. UNUSED(buft);
  10676. }
  10677. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10678. return GGML_VK_NAME "_Host";
  10679. UNUSED(buffer);
  10680. }
  10681. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10682. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10683. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10684. }
  10685. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10686. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10687. size += 32; // Behave like the CPU buffer type
  10688. void * ptr = nullptr;
  10689. try {
  10690. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10691. } catch (vk::SystemError& e) {
  10692. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10693. // fallback to cpu buffer
  10694. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10695. }
  10696. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10697. buffer->buft = buft;
  10698. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10699. return buffer;
  10700. UNUSED(buft);
  10701. }
  10702. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10703. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10704. UNUSED(buft);
  10705. }
  10706. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10707. return vk_instance.devices[0]->suballocation_block_size;
  10708. UNUSED(buft);
  10709. }
  10710. // Should be changed to return device-specific host buffer type
  10711. // but that probably requires changes in llama.cpp
  10712. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10713. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10714. /* .iface = */ {
  10715. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10716. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10717. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10718. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10719. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10720. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10721. },
  10722. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10723. /* .context = */ nullptr,
  10724. };
  10725. // Make sure device 0 is initialized
  10726. ggml_vk_instance_init();
  10727. ggml_vk_get_device(0);
  10728. return &ggml_backend_vk_buffer_type_host;
  10729. }
  10730. // backend
  10731. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10732. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10733. return ctx->name.c_str();
  10734. }
  10735. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10736. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10737. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10738. ggml_vk_cleanup(ctx);
  10739. delete ctx;
  10740. delete backend;
  10741. }
  10742. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10743. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10744. return &ctx->device->buffer_type;
  10745. }
  10746. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10747. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10748. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10749. 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");
  10750. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10751. vk_context transfer_ctx;
  10752. if (ctx->transfer_ctx.expired()) {
  10753. // Initialize new transfer context
  10754. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10755. ctx->transfer_ctx = transfer_ctx;
  10756. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10757. } else {
  10758. transfer_ctx = ctx->transfer_ctx.lock();
  10759. }
  10760. vk_buffer buf = buf_ctx->dev_buffer;
  10761. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10762. }
  10763. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10764. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10765. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10766. 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");
  10767. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10768. vk_context transfer_ctx;
  10769. if (ctx->transfer_ctx.expired()) {
  10770. // Initialize new transfer context
  10771. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10772. ctx->transfer_ctx = transfer_ctx;
  10773. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10774. } else {
  10775. transfer_ctx = ctx->transfer_ctx.lock();
  10776. }
  10777. vk_buffer buf = buf_ctx->dev_buffer;
  10778. auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  10779. bool ret = ggml_vk_buffer_read_async(transfer_ctx, buf, src_offset, data, size);
  10780. // If that failed, copy synchronously through a staging buffer
  10781. if (!ret) {
  10782. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  10783. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  10784. vk::BufferCopy buffer_cpy;
  10785. buffer_cpy.srcOffset = src_offset;
  10786. buffer_cpy.dstOffset = 0;
  10787. buffer_cpy.size = size;
  10788. transfer_ctx->s->buffer.copyBuffer(buf->buffer, ctx->sync_staging->buffer, { buffer_cpy });
  10789. deferred_memcpy(data, ctx->sync_staging->ptr, size, &transfer_ctx->out_memcpys);
  10790. ggml_vk_synchronize(ctx);
  10791. }
  10792. }
  10793. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10794. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10795. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10796. 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)) {
  10797. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10798. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10799. vk_context transfer_ctx;
  10800. if (ctx->transfer_ctx.expired()) {
  10801. // Initialize new transfer context
  10802. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10803. ctx->transfer_ctx = transfer_ctx;
  10804. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10805. } else {
  10806. transfer_ctx = ctx->transfer_ctx.lock();
  10807. }
  10808. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10809. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10810. 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));
  10811. return true;
  10812. }
  10813. return false;
  10814. }
  10815. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx) {
  10816. VK_LOG_DEBUG("ggml_vk_synchronize()");
  10817. bool do_transfer = !ctx->transfer_ctx.expired();
  10818. vk_context transfer_ctx;
  10819. if (do_transfer) {
  10820. transfer_ctx = ctx->transfer_ctx.lock();
  10821. ggml_vk_ctx_end(transfer_ctx);
  10822. for (auto& cpy : transfer_ctx->in_memcpys) {
  10823. memcpy(cpy.dst, cpy.src, cpy.n);
  10824. }
  10825. ggml_vk_submit(transfer_ctx, {});
  10826. ctx->submit_pending = true;
  10827. }
  10828. if (ctx->submit_pending) {
  10829. {
  10830. std::lock_guard<std::mutex> guard(queue_mutex);
  10831. ctx->device->compute_queue.queue.submit({}, ctx->fence);
  10832. }
  10833. ggml_vk_wait_for_fence(ctx);
  10834. ctx->submit_pending = false;
  10835. }
  10836. if (do_transfer) {
  10837. for (auto& cpy : transfer_ctx->out_memcpys) {
  10838. memcpy(cpy.dst, cpy.src, cpy.n);
  10839. }
  10840. ctx->transfer_ctx.reset();
  10841. }
  10842. }
  10843. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10844. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10845. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10846. ggml_vk_synchronize(ctx);
  10847. ggml_vk_graph_cleanup(ctx);
  10848. }
  10849. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10850. 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;
  10851. }
  10852. static bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  10853. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10854. return false;
  10855. }
  10856. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10857. // additional constraints specific to this fusion
  10858. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10859. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10860. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10861. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10862. // rms_norm only supports f32
  10863. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10864. mul->src[1]->type != GGML_TYPE_F32 ||
  10865. mul->type != GGML_TYPE_F32) {
  10866. return false;
  10867. }
  10868. // if rms_norm is the B operand, then we don't handle broadcast
  10869. if (rms_norm == mul->src[1] &&
  10870. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10871. return false;
  10872. }
  10873. // rms_norm shader assumes contiguous rows
  10874. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10875. return false;
  10876. }
  10877. }
  10878. auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) {
  10879. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  10880. // mat-vec only
  10881. if (ggml_nrows(mul) != 1) {
  10882. return false;
  10883. }
  10884. // shaders assume the types match
  10885. if (mul->type != bias->type) {
  10886. return false;
  10887. }
  10888. // shaders reuse the D shape for bias
  10889. if (!ggml_are_same_shape(mul, bias) ||
  10890. !ggml_are_same_stride(mul, bias)) {
  10891. return false;
  10892. }
  10893. // unaligned bias isn't handled
  10894. if (get_misalign_bytes(ctx, bias) != 0) {
  10895. return false;
  10896. }
  10897. return true;
  10898. };
  10899. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  10900. // additional constraints specific to this fusion
  10901. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10902. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10903. if (!mm_add_ok(mul, add)) {
  10904. return false;
  10905. }
  10906. if (ops.size() == 3) {
  10907. if (ops.begin()[2] != GGML_OP_ADD) {
  10908. return false;
  10909. }
  10910. if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) {
  10911. return false;
  10912. }
  10913. }
  10914. }
  10915. auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) {
  10916. const ggml_tensor *scale = mul->src[1];
  10917. if (mmid != mul->src[0]) {
  10918. return false;
  10919. }
  10920. // mat-vec only
  10921. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10922. return false;
  10923. }
  10924. // shaders assume the types match
  10925. if (mmid->type != scale->type) {
  10926. return false;
  10927. }
  10928. // shaders assume the bias is contiguous
  10929. if (!ggml_is_contiguous(scale)) {
  10930. return false;
  10931. }
  10932. // unaligned bias isn't handled
  10933. if (get_misalign_bytes(ctx, scale) != 0) {
  10934. return false;
  10935. }
  10936. // shader only indexes by expert index
  10937. if (scale->ne[0] != 1 ||
  10938. scale->ne[1] != mul->ne[1] ||
  10939. scale->ne[2] != 1 ||
  10940. scale->ne[3] != 1) {
  10941. return false;
  10942. }
  10943. return true;
  10944. };
  10945. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  10946. // additional constraints specific to this fusion
  10947. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10948. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10949. const ggml_tensor *bias = add->src[1];
  10950. if (mul != add->src[0]) {
  10951. return false;
  10952. }
  10953. // mat-vec only
  10954. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10955. return false;
  10956. }
  10957. // shaders assume the types match
  10958. if (mul->type != bias->type) {
  10959. return false;
  10960. }
  10961. // shaders assume the bias is contiguous
  10962. if (!ggml_is_contiguous(bias)) {
  10963. return false;
  10964. }
  10965. // the ID tensor must be the same for mul_mat_id and add_id
  10966. if (mul->src[2] != add->src[2]) {
  10967. return false;
  10968. }
  10969. // unaligned bias isn't handled
  10970. if (get_misalign_bytes(ctx, bias) != 0) {
  10971. return false;
  10972. }
  10973. if (ops.size() == 3) {
  10974. if (ops.begin()[2] != GGML_OP_MUL) {
  10975. return false;
  10976. }
  10977. const ggml_tensor *mul = cgraph->nodes[node_idx + 2];
  10978. return mmid_mul_ok(add, mul);
  10979. }
  10980. }
  10981. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  10982. // additional constraints specific to this fusion
  10983. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  10984. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10985. if (!mmid_mul_ok(mmid, mul)) {
  10986. return false;
  10987. }
  10988. }
  10989. return true;
  10990. }
  10991. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10992. int node_idx, topk_moe_mode mode) {
  10993. const ggml_tensor * softmax;
  10994. const ggml_tensor * weights;
  10995. switch (mode) {
  10996. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  10997. softmax = cgraph->nodes[node_idx + 0];
  10998. weights = cgraph->nodes[node_idx + 9];
  10999. break;
  11000. case TOPK_MOE_EARLY_SOFTMAX:
  11001. softmax = cgraph->nodes[node_idx + 0];
  11002. weights = cgraph->nodes[node_idx + 4];
  11003. break;
  11004. case TOPK_MOE_LATE_SOFTMAX:
  11005. softmax = cgraph->nodes[node_idx + 4];
  11006. weights = cgraph->nodes[node_idx + 5];
  11007. break;
  11008. default:
  11009. return false;
  11010. }
  11011. const float * op_params = (const float *)softmax->op_params;
  11012. float scale = op_params[0];
  11013. float max_bias = op_params[1];
  11014. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  11015. return false;
  11016. }
  11017. if (scale != 1.0f || max_bias != 0.0f) {
  11018. return false;
  11019. }
  11020. // don't fuse when masks or sinks are present
  11021. if (softmax->src[1] || softmax->src[2]) {
  11022. return false;
  11023. }
  11024. const int n_expert = softmax->ne[0];
  11025. if (n_expert > (1 << (num_topk_moe_pipelines-1))) {
  11026. return false;
  11027. }
  11028. if (!ctx->device->subgroup_arithmetic ||
  11029. !ctx->device->subgroup_shuffle ||
  11030. !ctx->device->subgroup_require_full_support ||
  11031. ctx->device->disable_fusion) {
  11032. return false;
  11033. }
  11034. return true;
  11035. }
  11036. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11037. int node_idx) {
  11038. GGML_UNUSED(ctx);
  11039. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  11040. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  11041. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  11042. // ne3 not tested
  11043. if (rope->src[0]->ne[3] != 1) {
  11044. return false;
  11045. }
  11046. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  11047. return false;
  11048. }
  11049. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  11050. return false;
  11051. }
  11052. // The view should flatten two dims of rope into one dim
  11053. if (!ggml_is_contiguous(view) ||
  11054. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  11055. return false;
  11056. }
  11057. // Only norm/neox shaders have the fusion code
  11058. const int mode = ((const int32_t *) rope->op_params)[2];
  11059. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
  11060. return false;
  11061. }
  11062. return true;
  11063. }
  11064. // Check whether the tensors overlap in memory but are not equal.
  11065. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  11066. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  11067. // to overlap if they are exactly equal.
  11068. // XXX TODO this check is probably missing from several fusion optimizations.
  11069. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  11070. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  11071. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  11072. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  11073. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  11074. if (a_buf == b_buf) {
  11075. auto a_base = vk_tensor_offset(a) + a->view_offs;
  11076. auto a_size = ggml_nbytes(a);
  11077. auto b_base = vk_tensor_offset(b) + b->view_offs;
  11078. auto b_size = ggml_nbytes(b);
  11079. if (a_base == b_base && a_size == b_size) {
  11080. return false;
  11081. }
  11082. if ((b_base <= a_base && a_base < b_base + b_size) ||
  11083. (a_base <= b_base && b_base < a_base + a_size)) {
  11084. return true;
  11085. }
  11086. }
  11087. return false;
  11088. }
  11089. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11090. int node_idx) {
  11091. GGML_UNUSED(ctx);
  11092. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  11093. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11094. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  11095. const int mode = ((const int32_t *) rope->op_params)[2];
  11096. // noncontig tensors aren't tested, and don't seem common in practice
  11097. if (!ggml_is_contiguous(rms) ||
  11098. !ggml_is_contiguous(mul) ||
  11099. !ggml_is_contiguous(rope)) {
  11100. return false;
  11101. }
  11102. // only norm/neox are handled in the shader
  11103. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  11104. return false;
  11105. }
  11106. // shared memory size for passing data from mul->rope
  11107. if (mul->ne[0] > 1024) {
  11108. return false;
  11109. }
  11110. // must not overwrite srcs in a way that's not elementwise
  11111. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  11112. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  11113. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  11114. return false;
  11115. }
  11116. // conditions for pipeline creation
  11117. if (!(ctx->device->float_controls_rte_fp16 &&
  11118. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= ctx->device->properties.limits.maxPushConstantsSize)) {
  11119. return false;
  11120. }
  11121. return true;
  11122. }
  11123. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  11124. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  11125. if (first_node->op != GGML_OP_ADD) {
  11126. return 0;
  11127. }
  11128. if (!ctx->device->multi_add) {
  11129. return 0;
  11130. }
  11131. int32_t num_adds = 1;
  11132. while (node_idx + num_adds < cgraph->n_nodes &&
  11133. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  11134. num_adds < MAX_FUSED_ADDS) {
  11135. num_adds++;
  11136. }
  11137. // The shader currently requires same shapes (but different strides are allowed),
  11138. // everything f32, and no misalignment
  11139. for (int32_t i = 0; i < num_adds; ++i) {
  11140. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  11141. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  11142. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  11143. next_node->type != GGML_TYPE_F32 ||
  11144. next_node->src[0]->type != GGML_TYPE_F32 ||
  11145. next_node->src[1]->type != GGML_TYPE_F32 ||
  11146. get_misalign_bytes(ctx, next_node) ||
  11147. get_misalign_bytes(ctx, next_node->src[0]) ||
  11148. get_misalign_bytes(ctx, next_node->src[1])) {
  11149. num_adds = i;
  11150. }
  11151. }
  11152. // Verify we can fuse these
  11153. ggml_op adds[MAX_FUSED_ADDS];
  11154. for (int32_t i = 0; i < num_adds; ++i) {
  11155. adds[i] = GGML_OP_ADD;
  11156. }
  11157. // decrease num_adds if they can't all be fused
  11158. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  11159. num_adds--;
  11160. }
  11161. // a single add is not "fused", so just return zero
  11162. if (num_adds == 1) {
  11163. return 0;
  11164. }
  11165. return num_adds;
  11166. }
  11167. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  11168. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  11169. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11170. if (vk_instance.debug_utils_support) {
  11171. vk::DebugUtilsLabelEXT dul = {};
  11172. dul.pLabelName = "ggml_backend_vk_graph_compute";
  11173. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  11174. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  11175. }
  11176. ctx->prealloc_size_add_rms_partials_offset = 0;
  11177. ctx->do_add_rms_partials = false;
  11178. ctx->do_add_rms_partials_offset_calculation = false;
  11179. int last_node = cgraph->n_nodes - 1;
  11180. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  11181. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  11182. last_node -= 1;
  11183. }
  11184. // Reserve tensor context space for all nodes
  11185. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  11186. bool first_node_in_batch = true; // true if next node will be first node in a batch
  11187. int submit_node_idx = 0; // index to first node in a batch
  11188. vk_context compute_ctx;
  11189. if (vk_perf_logger_enabled) {
  11190. // allocate/resize the query pool
  11191. if (ctx->num_queries < cgraph->n_nodes + 1) {
  11192. if (ctx->query_pool) {
  11193. ctx->device->device.destroyQueryPool(ctx->query_pool);
  11194. }
  11195. vk::QueryPoolCreateInfo query_create_info;
  11196. query_create_info.queryType = vk::QueryType::eTimestamp;
  11197. query_create_info.queryCount = cgraph->n_nodes + 100;
  11198. ctx->query_pool = ctx->device->device.createQueryPool(query_create_info);
  11199. ctx->num_queries = query_create_info.queryCount;
  11200. ctx->query_fusion_names.resize(ctx->num_queries);
  11201. ctx->query_nodes.resize(ctx->num_queries);
  11202. }
  11203. ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1);
  11204. std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr);
  11205. std::fill(ctx->query_nodes.begin(), ctx->query_nodes.end(), nullptr);
  11206. GGML_ASSERT(ctx->compute_ctx.expired());
  11207. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11208. ctx->compute_ctx = compute_ctx;
  11209. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11210. ctx->query_idx = 0;
  11211. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11212. }
  11213. ctx->prealloc_y_last_pipeline_used = nullptr;
  11214. ctx->prealloc_y_last_tensor_used = nullptr;
  11215. if (ctx->prealloc_size_add_rms_partials) {
  11216. ggml_vk_preallocate_buffers(ctx, nullptr);
  11217. if (ctx->compute_ctx.expired()) {
  11218. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11219. ctx->compute_ctx = compute_ctx;
  11220. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11221. } else {
  11222. compute_ctx = ctx->compute_ctx.lock();
  11223. }
  11224. // initialize partial sums to zero.
  11225. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  11226. ggml_vk_sync_buffers(ctx, compute_ctx);
  11227. }
  11228. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  11229. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  11230. // (and scaled down based on model size, so smaller models submit earlier).
  11231. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  11232. int nodes_per_submit = 100;
  11233. int submitted_nodes = 0;
  11234. int submit_count = 0;
  11235. uint64_t mul_mat_bytes = 0;
  11236. uint64_t total_mul_mat_bytes = 0;
  11237. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  11238. for (int i = 0; i < cgraph->n_nodes; i++) {
  11239. if (first_node_in_batch) {
  11240. submit_node_idx = i;
  11241. }
  11242. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11243. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  11244. mul_mat_bytes += bytes;
  11245. total_mul_mat_bytes += bytes;
  11246. }
  11247. const char *fusion_string {};
  11248. if (!ctx->device->disable_fusion) {
  11249. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11250. if (num_adds) {
  11251. ctx->num_additional_fused_ops = num_adds - 1;
  11252. fusion_string = "MULTI_ADD";
  11253. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) {
  11254. ctx->num_additional_fused_ops = 2;
  11255. fusion_string = "MUL_MAT_ADD_ADD";
  11256. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11257. ctx->num_additional_fused_ops = 1;
  11258. fusion_string = "MUL_MAT_ADD";
  11259. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) {
  11260. ctx->num_additional_fused_ops = 2;
  11261. fusion_string = "MUL_MAT_ID_ADD_ID_MUL";
  11262. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11263. ctx->num_additional_fused_ops = 1;
  11264. fusion_string = "MUL_MAT_ID_ADD_ID";
  11265. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  11266. ctx->num_additional_fused_ops = 1;
  11267. fusion_string = "MUL_MAT_ID_MUL";
  11268. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 4 }) &&
  11269. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  11270. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  11271. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  11272. ctx->num_additional_fused_ops = 4;
  11273. fusion_string = "RMS_NORM_MUL_ROPE_VIEW_SET_ROWS";
  11274. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  11275. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  11276. ctx->num_additional_fused_ops = 2;
  11277. fusion_string = "RMS_NORM_MUL_ROPE";
  11278. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11279. ctx->num_additional_fused_ops = 1;
  11280. fusion_string = "RMS_NORM_MUL";
  11281. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11282. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11283. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11284. ctx->num_additional_fused_ops = 2;
  11285. fusion_string = "ROPE_VIEW_SET_ROWS";
  11286. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11287. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11288. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11289. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11290. // view of argsort writes to memory
  11291. ctx->fused_ops_write_mask |= 1 << 3;
  11292. fusion_string = "TOPK_MOE_EARLY_SOFTMAX_NORM";
  11293. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11294. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11295. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11296. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11297. // view of argsort writes to memory
  11298. ctx->fused_ops_write_mask |= 1 << 3;
  11299. fusion_string = "TOPK_MOE_EARLY_SOFTMAX";
  11300. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11301. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11302. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11303. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11304. // view of argsort writes to memory
  11305. ctx->fused_ops_write_mask |= 1 << 1;
  11306. fusion_string = "TOPK_MOE_LATE_SOFTMAX";
  11307. }
  11308. }
  11309. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  11310. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  11311. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  11312. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11313. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11314. (i + ctx->num_additional_fused_ops >= last_node) ||
  11315. (almost_ready && !ctx->almost_ready_fence_pending);
  11316. bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, i + ctx->num_additional_fused_ops >= last_node, almost_ready, submit);
  11317. if (vk_perf_logger_enabled && enqueued) {
  11318. if (ctx->compute_ctx.expired()) {
  11319. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11320. ctx->compute_ctx = compute_ctx;
  11321. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11322. } else {
  11323. compute_ctx = ctx->compute_ctx.lock();
  11324. }
  11325. ctx->query_nodes[ctx->query_idx] = cgraph->nodes[i];
  11326. ctx->query_fusion_names[ctx->query_idx] = fusion_string;
  11327. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11328. }
  11329. if (enqueued) {
  11330. ++submitted_nodes;
  11331. #ifndef GGML_VULKAN_CHECK_RESULTS
  11332. if (first_node_in_batch) {
  11333. first_node_in_batch = false;
  11334. }
  11335. #endif
  11336. }
  11337. if (submit && enqueued) {
  11338. first_node_in_batch = true;
  11339. submitted_nodes = 0;
  11340. mul_mat_bytes = 0;
  11341. if (submit_count < 3) {
  11342. mul_mat_bytes_per_submit *= 2;
  11343. }
  11344. submit_count++;
  11345. }
  11346. i += ctx->num_additional_fused_ops;
  11347. ctx->num_additional_fused_ops = 0;
  11348. ctx->fused_ops_write_mask = 0;
  11349. }
  11350. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11351. if (vk_perf_logger_enabled) {
  11352. // End the command buffer and submit/wait
  11353. GGML_ASSERT(!ctx->compute_ctx.expired());
  11354. compute_ctx = ctx->compute_ctx.lock();
  11355. ggml_vk_ctx_end(compute_ctx);
  11356. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11357. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11358. ctx->device->device.resetFences({ ctx->device->fence });
  11359. // Get the results and pass them to the logger
  11360. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11361. VK_CHECK(ctx->device->device.getQueryPoolResults(ctx->query_pool, 0, ctx->query_idx, (cgraph->n_nodes + 1)*sizeof(uint64_t), timestamps.data(), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait), "get timestamp results");
  11362. for (int i = 1; i < ctx->query_idx; i++) {
  11363. auto node = ctx->query_nodes[i];
  11364. auto name = ctx->query_fusion_names[i];
  11365. ctx->perf_logger->log_timing(node, name, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11366. }
  11367. ctx->perf_logger->print_timings();
  11368. }
  11369. if (!ctx->device->support_async) {
  11370. ggml_vk_synchronize(ctx);
  11371. }
  11372. return GGML_STATUS_SUCCESS;
  11373. UNUSED(backend);
  11374. }
  11375. // Sort the graph for improved parallelism.
  11376. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11377. {
  11378. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11379. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11380. if (ctx->device->disable_graph_optimize) {
  11381. return;
  11382. }
  11383. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11384. return node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE;
  11385. };
  11386. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11387. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11388. if (dst->src[s] == src) {
  11389. return true;
  11390. }
  11391. }
  11392. // implicit dependency if they view the same tensor
  11393. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11394. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11395. if (dst2 == src2) {
  11396. return true;
  11397. }
  11398. return false;
  11399. };
  11400. std::vector<ggml_tensor *> new_order;
  11401. std::vector<bool> used(graph->n_nodes, false);
  11402. std::set<ggml_tensor *> used_node_set;
  11403. int first_unused = 0;
  11404. while (first_unused < graph->n_nodes) {
  11405. std::vector<int> current_set;
  11406. // Check for fusion patterns and avoid reordering them
  11407. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11408. if (start + (int)pattern.size() <= graph->n_nodes) {
  11409. bool is_pattern = true;
  11410. for (size_t j = 0; j < pattern.size(); ++j) {
  11411. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11412. is_pattern = false;
  11413. }
  11414. }
  11415. return is_pattern;
  11416. }
  11417. return false;
  11418. };
  11419. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11420. if (match_pattern(pattern, first_unused)) {
  11421. for (size_t j = 0; j < pattern.size(); ++j) {
  11422. new_order.push_back(graph->nodes[first_unused + j]);
  11423. used_node_set.insert(graph->nodes[first_unused + j]);
  11424. used[first_unused + j] = true;
  11425. }
  11426. while (first_unused < graph->n_nodes && used[first_unused]) {
  11427. first_unused++;
  11428. }
  11429. return true;
  11430. }
  11431. return false;
  11432. };
  11433. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11434. continue;
  11435. }
  11436. if (keep_pattern(topk_moe_early_softmax)) {
  11437. continue;
  11438. }
  11439. if (keep_pattern(topk_moe_late_softmax)) {
  11440. continue;
  11441. }
  11442. // First, grab the next unused node.
  11443. current_set.push_back(first_unused);
  11444. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11445. // haven't already been run. Nodes that have already been run have used[i] set
  11446. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11447. // that we support (e.g. RMS_NORM + MUL).
  11448. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11449. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11450. const int NUM_TO_CHECK = 20;
  11451. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11452. if (used[j]) {
  11453. continue;
  11454. }
  11455. if (is_empty(graph->nodes[j])) {
  11456. continue;
  11457. }
  11458. // Don't pull forward nodes from fusion patterns
  11459. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11460. match_pattern(topk_moe_early_softmax, j) ||
  11461. match_pattern(topk_moe_late_softmax, j)) {
  11462. continue;
  11463. }
  11464. bool ok = true;
  11465. for (int c = first_unused; c < j; ++c) {
  11466. if (!used[c] &&
  11467. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11468. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11469. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11470. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11471. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL)) {
  11472. ok = false;
  11473. break;
  11474. }
  11475. }
  11476. if (ok) {
  11477. current_set.push_back(j);
  11478. int rope_idx = j;
  11479. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11480. if (j > 0 &&
  11481. graph->nodes[j]->op == GGML_OP_MUL &&
  11482. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11483. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11484. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11485. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11486. // Check that other srcs are already valid
  11487. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11488. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11489. rope_idx = k;
  11490. current_set.push_back(rope_idx);
  11491. used[rope_idx] = true;
  11492. break;
  11493. }
  11494. }
  11495. }
  11496. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11497. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11498. int view_idx = -1;
  11499. int set_rows_idx = -1;
  11500. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11501. if (view_idx == -1 &&
  11502. graph->nodes[k]->op == GGML_OP_VIEW &&
  11503. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11504. view_idx = k;
  11505. continue;
  11506. }
  11507. if (view_idx != -1 &&
  11508. set_rows_idx == -1 &&
  11509. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11510. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11511. set_rows_idx = k;
  11512. break;
  11513. }
  11514. }
  11515. if (set_rows_idx != -1) {
  11516. current_set.push_back(view_idx);
  11517. current_set.push_back(set_rows_idx);
  11518. used[view_idx] = true;
  11519. used[set_rows_idx] = true;
  11520. }
  11521. }
  11522. // Look for MUL_MAT_ID + ADD_ID + MUL
  11523. if (j > 0 &&
  11524. graph->nodes[j]->op == GGML_OP_ADD_ID &&
  11525. graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) {
  11526. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11527. if (graph->nodes[k]->op == GGML_OP_MUL &&
  11528. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11529. // src1 must either be weights or already processed
  11530. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11531. current_set.push_back(k);
  11532. used[k] = true;
  11533. break;
  11534. }
  11535. }
  11536. }
  11537. // Look for MUL_MAT + ADD + ADD
  11538. if (j > 0 &&
  11539. graph->nodes[j]->op == GGML_OP_ADD &&
  11540. graph->nodes[j-1]->op == GGML_OP_MUL_MAT) {
  11541. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11542. if (graph->nodes[k]->op == GGML_OP_ADD &&
  11543. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11544. // src1 must either be weights or already processed
  11545. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11546. current_set.push_back(k);
  11547. used[k] = true;
  11548. break;
  11549. }
  11550. }
  11551. }
  11552. }
  11553. }
  11554. // Second pass grabs view nodes.
  11555. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11556. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11557. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11558. if (used[j]) {
  11559. continue;
  11560. }
  11561. if (!is_empty(graph->nodes[j])) {
  11562. continue;
  11563. }
  11564. bool ok = true;
  11565. for (int c = first_unused; c < j; ++c) {
  11566. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11567. // skip views whose srcs haven't been processed.
  11568. if (!used[c] &&
  11569. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11570. !c_in_current_set) {
  11571. ok = false;
  11572. break;
  11573. }
  11574. }
  11575. if (ok) {
  11576. current_set.push_back(j);
  11577. }
  11578. }
  11579. }
  11580. // Push the current set into new_order
  11581. for (auto c : current_set) {
  11582. new_order.push_back(graph->nodes[c]);
  11583. used_node_set.insert(graph->nodes[c]);
  11584. used[c] = true;
  11585. }
  11586. while (first_unused < graph->n_nodes && used[first_unused]) {
  11587. first_unused++;
  11588. }
  11589. }
  11590. // Replace the graph with the new order.
  11591. for (int i = 0; i < graph->n_nodes; ++i) {
  11592. graph->nodes[i] = new_order[i];
  11593. }
  11594. }
  11595. // TODO: enable async and synchronize
  11596. static ggml_backend_i ggml_backend_vk_interface = {
  11597. /* .get_name = */ ggml_backend_vk_name,
  11598. /* .free = */ ggml_backend_vk_free,
  11599. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  11600. /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async,
  11601. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11602. /* .synchronize = */ ggml_backend_vk_synchronize,
  11603. /* .graph_plan_create = */ NULL,
  11604. /* .graph_plan_free = */ NULL,
  11605. /* .graph_plan_update = */ NULL,
  11606. /* .graph_plan_compute = */ NULL,
  11607. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11608. /* .event_record = */ NULL,
  11609. /* .event_wait = */ NULL,
  11610. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11611. };
  11612. static ggml_guid_t ggml_backend_vk_guid() {
  11613. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11614. return &guid;
  11615. }
  11616. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11617. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11618. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11619. ggml_vk_init(ctx, dev_num);
  11620. ggml_backend_t vk_backend = new ggml_backend {
  11621. /* .guid = */ ggml_backend_vk_guid(),
  11622. /* .iface = */ ggml_backend_vk_interface,
  11623. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11624. /* .context = */ ctx,
  11625. };
  11626. if (!ctx->device->support_async) {
  11627. vk_backend->iface.get_tensor_async = nullptr;
  11628. }
  11629. return vk_backend;
  11630. }
  11631. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11632. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11633. }
  11634. int ggml_backend_vk_get_device_count() {
  11635. return ggml_vk_get_device_count();
  11636. }
  11637. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11638. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11639. int dev_idx = vk_instance.device_indices[device];
  11640. ggml_vk_get_device_description(dev_idx, description, description_size);
  11641. }
  11642. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11643. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11644. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11645. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11646. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11647. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11648. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  11649. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  11650. if (membudget_supported) {
  11651. memprops.pNext = &budgetprops;
  11652. }
  11653. vkdev.getMemoryProperties2(&memprops);
  11654. *total = 0;
  11655. *free = 0;
  11656. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11657. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11658. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  11659. *total += heap.size;
  11660. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11661. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11662. } else {
  11663. *free += heap.size;
  11664. }
  11665. }
  11666. }
  11667. }
  11668. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11669. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11670. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11671. vk::PhysicalDeviceProperties2 props = {};
  11672. device.getProperties2(&props);
  11673. return props.properties.deviceType;
  11674. }
  11675. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11676. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11677. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11678. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11679. bool ext_support = false;
  11680. for (const auto& properties : ext_props) {
  11681. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11682. ext_support = true;
  11683. break;
  11684. }
  11685. }
  11686. if (!ext_support) {
  11687. return "";
  11688. }
  11689. vk::PhysicalDeviceProperties2 props = {};
  11690. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11691. props.pNext = &pci_bus_info;
  11692. device.getProperties2(&props);
  11693. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11694. const uint32_t pci_bus = pci_bus_info.pciBus;
  11695. const uint32_t pci_device = pci_bus_info.pciDevice;
  11696. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11697. char pci_bus_id[16] = {};
  11698. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11699. return std::string(pci_bus_id);
  11700. }
  11701. //////////////////////////
  11702. struct ggml_backend_vk_device_context {
  11703. size_t device;
  11704. std::string name;
  11705. std::string description;
  11706. bool is_integrated_gpu;
  11707. std::string pci_bus_id;
  11708. };
  11709. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11710. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11711. return ctx->name.c_str();
  11712. }
  11713. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11714. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11715. return ctx->description.c_str();
  11716. }
  11717. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11718. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11719. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11720. }
  11721. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11722. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11723. return ggml_backend_vk_buffer_type(ctx->device);
  11724. }
  11725. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11726. UNUSED(dev);
  11727. return ggml_backend_vk_host_buffer_type();
  11728. }
  11729. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11730. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11731. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11732. }
  11733. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11734. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11735. props->name = ggml_backend_vk_device_get_name(dev);
  11736. props->description = ggml_backend_vk_device_get_description(dev);
  11737. props->type = ggml_backend_vk_device_get_type(dev);
  11738. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11739. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11740. props->caps = {
  11741. /* .async = */ false,
  11742. /* .host_buffer = */ true,
  11743. /* .buffer_from_host_ptr = */ false,
  11744. /* .events = */ false,
  11745. };
  11746. }
  11747. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11748. UNUSED(params);
  11749. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11750. return ggml_backend_vk_init(ctx->device);
  11751. }
  11752. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11753. switch (op->op) {
  11754. case GGML_OP_UNARY:
  11755. switch (ggml_get_unary_op(op)) {
  11756. case GGML_UNARY_OP_EXP:
  11757. case GGML_UNARY_OP_GELU:
  11758. case GGML_UNARY_OP_GELU_ERF:
  11759. case GGML_UNARY_OP_GELU_QUICK:
  11760. case GGML_UNARY_OP_SILU:
  11761. case GGML_UNARY_OP_RELU:
  11762. case GGML_UNARY_OP_NEG:
  11763. case GGML_UNARY_OP_TANH:
  11764. case GGML_UNARY_OP_SIGMOID:
  11765. case GGML_UNARY_OP_HARDSIGMOID:
  11766. case GGML_UNARY_OP_HARDSWISH:
  11767. case GGML_UNARY_OP_ABS:
  11768. case GGML_UNARY_OP_SOFTPLUS:
  11769. case GGML_UNARY_OP_STEP:
  11770. case GGML_UNARY_OP_ROUND:
  11771. case GGML_UNARY_OP_CEIL:
  11772. case GGML_UNARY_OP_FLOOR:
  11773. case GGML_UNARY_OP_TRUNC:
  11774. return ggml_is_contiguous(op->src[0]) &&
  11775. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11776. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11777. (op->src[0]->type == op->type);
  11778. default:
  11779. return false;
  11780. }
  11781. case GGML_OP_GLU:
  11782. switch (ggml_get_glu_op(op)) {
  11783. case GGML_GLU_OP_GEGLU:
  11784. case GGML_GLU_OP_REGLU:
  11785. case GGML_GLU_OP_SWIGLU:
  11786. case GGML_GLU_OP_SWIGLU_OAI:
  11787. case GGML_GLU_OP_GEGLU_ERF:
  11788. case GGML_GLU_OP_GEGLU_QUICK:
  11789. return ggml_is_contiguous(op->src[0]) &&
  11790. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11791. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11792. (op->src[0]->type == op->type);
  11793. default:
  11794. return false;
  11795. }
  11796. case GGML_OP_MUL_MAT:
  11797. case GGML_OP_MUL_MAT_ID:
  11798. {
  11799. ggml_type src0_type = op->src[0]->type;
  11800. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11801. const vk_device& device = ggml_vk_get_device(ctx->device);
  11802. if (op->op == GGML_OP_MUL_MAT_ID) {
  11803. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11804. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11805. return false;
  11806. }
  11807. }
  11808. switch (src0_type) {
  11809. case GGML_TYPE_F32:
  11810. case GGML_TYPE_F16:
  11811. case GGML_TYPE_BF16:
  11812. case GGML_TYPE_Q4_0:
  11813. case GGML_TYPE_Q4_1:
  11814. case GGML_TYPE_Q5_0:
  11815. case GGML_TYPE_Q5_1:
  11816. case GGML_TYPE_Q8_0:
  11817. case GGML_TYPE_Q2_K:
  11818. case GGML_TYPE_Q3_K:
  11819. case GGML_TYPE_Q4_K:
  11820. case GGML_TYPE_Q5_K:
  11821. case GGML_TYPE_Q6_K:
  11822. case GGML_TYPE_IQ1_S:
  11823. case GGML_TYPE_IQ1_M:
  11824. case GGML_TYPE_IQ2_XXS:
  11825. case GGML_TYPE_IQ2_XS:
  11826. case GGML_TYPE_IQ2_S:
  11827. case GGML_TYPE_IQ3_XXS:
  11828. case GGML_TYPE_IQ3_S:
  11829. case GGML_TYPE_IQ4_XS:
  11830. case GGML_TYPE_IQ4_NL:
  11831. case GGML_TYPE_MXFP4:
  11832. break;
  11833. default:
  11834. return false;
  11835. }
  11836. struct ggml_tensor * a;
  11837. struct ggml_tensor * b;
  11838. if (op->op == GGML_OP_MUL_MAT) {
  11839. a = op->src[0];
  11840. b = op->src[1];
  11841. } else {
  11842. a = op->src[2];
  11843. b = op->src[1];
  11844. }
  11845. if (a->ne[3] != b->ne[3]) {
  11846. return false;
  11847. }
  11848. if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) ||
  11849. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  11850. return false;
  11851. }
  11852. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  11853. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  11854. // So don't support this combination for now.
  11855. return false;
  11856. }
  11857. return true;
  11858. }
  11859. case GGML_OP_FLASH_ATTN_EXT:
  11860. {
  11861. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11862. auto device = ggml_vk_get_device(ctx->device);
  11863. bool coopmat2 = device->coopmat2;
  11864. uint32_t HSK = op->src[1]->ne[0];
  11865. uint32_t HSV = op->src[2]->ne[0];
  11866. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  11867. return false;
  11868. }
  11869. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  11870. return false;
  11871. }
  11872. if (op->src[0]->type != GGML_TYPE_F32) {
  11873. return false;
  11874. }
  11875. if (op->type != GGML_TYPE_F32) {
  11876. return false;
  11877. }
  11878. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  11879. return false;
  11880. }
  11881. // It's straightforward to support different K/V dequant, but would
  11882. // significantly increase the number of pipelines
  11883. if (op->src[1]->type != op->src[2]->type) {
  11884. return false;
  11885. }
  11886. switch (op->src[1]->type) {
  11887. case GGML_TYPE_F16:
  11888. case GGML_TYPE_F32:
  11889. case GGML_TYPE_Q4_0:
  11890. case GGML_TYPE_Q8_0:
  11891. // supported in scalar and coopmat2 paths
  11892. break;
  11893. case GGML_TYPE_Q4_1:
  11894. case GGML_TYPE_Q5_0:
  11895. case GGML_TYPE_Q5_1:
  11896. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  11897. //case GGML_TYPE_Q2_K:
  11898. //case GGML_TYPE_Q3_K:
  11899. //case GGML_TYPE_Q4_K:
  11900. //case GGML_TYPE_Q5_K:
  11901. //case GGML_TYPE_Q6_K:
  11902. //case GGML_TYPE_IQ1_S:
  11903. //case GGML_TYPE_IQ1_M:
  11904. //case GGML_TYPE_IQ2_XXS:
  11905. //case GGML_TYPE_IQ2_XS:
  11906. //case GGML_TYPE_IQ2_S:
  11907. //case GGML_TYPE_IQ3_XXS:
  11908. //case GGML_TYPE_IQ3_S:
  11909. //case GGML_TYPE_IQ4_XS:
  11910. case GGML_TYPE_IQ4_NL:
  11911. // currently supported only in coopmat2 path
  11912. if (!coopmat2) {
  11913. return false;
  11914. }
  11915. break;
  11916. default:
  11917. return false;
  11918. }
  11919. if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) {
  11920. // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll
  11921. return false;
  11922. }
  11923. return true;
  11924. }
  11925. case GGML_OP_GET_ROWS:
  11926. {
  11927. switch (op->src[0]->type) {
  11928. case GGML_TYPE_F32:
  11929. case GGML_TYPE_F16:
  11930. case GGML_TYPE_BF16:
  11931. case GGML_TYPE_Q4_0:
  11932. case GGML_TYPE_Q4_1:
  11933. case GGML_TYPE_Q5_0:
  11934. case GGML_TYPE_Q5_1:
  11935. case GGML_TYPE_Q8_0:
  11936. case GGML_TYPE_Q2_K:
  11937. case GGML_TYPE_Q3_K:
  11938. case GGML_TYPE_Q4_K:
  11939. case GGML_TYPE_Q5_K:
  11940. case GGML_TYPE_Q6_K:
  11941. case GGML_TYPE_IQ1_S:
  11942. case GGML_TYPE_IQ1_M:
  11943. case GGML_TYPE_IQ2_XXS:
  11944. case GGML_TYPE_IQ2_XS:
  11945. case GGML_TYPE_IQ2_S:
  11946. case GGML_TYPE_IQ3_XXS:
  11947. case GGML_TYPE_IQ3_S:
  11948. case GGML_TYPE_IQ4_XS:
  11949. case GGML_TYPE_IQ4_NL:
  11950. case GGML_TYPE_MXFP4:
  11951. case GGML_TYPE_I32:
  11952. return true;
  11953. default:
  11954. return false;
  11955. }
  11956. }
  11957. case GGML_OP_SET_ROWS:
  11958. {
  11959. switch (op->type) {
  11960. case GGML_TYPE_F32:
  11961. case GGML_TYPE_F16:
  11962. case GGML_TYPE_BF16:
  11963. case GGML_TYPE_Q4_0:
  11964. case GGML_TYPE_Q4_1:
  11965. case GGML_TYPE_Q5_0:
  11966. case GGML_TYPE_Q5_1:
  11967. case GGML_TYPE_Q8_0:
  11968. case GGML_TYPE_IQ4_NL:
  11969. return true;
  11970. default:
  11971. return false;
  11972. }
  11973. }
  11974. case GGML_OP_CONT:
  11975. case GGML_OP_CPY:
  11976. case GGML_OP_DUP:
  11977. {
  11978. ggml_type src0_type = op->src[0]->type;
  11979. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  11980. if (src0_type == GGML_TYPE_F32) {
  11981. switch (src1_type) {
  11982. case GGML_TYPE_F32:
  11983. case GGML_TYPE_F16:
  11984. case GGML_TYPE_BF16:
  11985. case GGML_TYPE_Q4_0:
  11986. case GGML_TYPE_Q4_1:
  11987. case GGML_TYPE_Q5_0:
  11988. case GGML_TYPE_Q5_1:
  11989. case GGML_TYPE_Q8_0:
  11990. case GGML_TYPE_IQ4_NL:
  11991. return true;
  11992. default:
  11993. break;
  11994. }
  11995. }
  11996. if (src1_type == GGML_TYPE_F32) {
  11997. switch (src0_type) {
  11998. case GGML_TYPE_F16:
  11999. case GGML_TYPE_Q4_0:
  12000. case GGML_TYPE_Q4_1:
  12001. case GGML_TYPE_Q5_0:
  12002. case GGML_TYPE_Q5_1:
  12003. case GGML_TYPE_Q8_0:
  12004. case GGML_TYPE_IQ4_NL:
  12005. return true;
  12006. default:
  12007. break;
  12008. }
  12009. }
  12010. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  12011. return true;
  12012. }
  12013. if (
  12014. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  12015. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  12016. ) {
  12017. return true;
  12018. }
  12019. // We can handle copying from a type to the same type if it's
  12020. // either not quantized or is quantized and contiguous.
  12021. // We use f16 or f32 shaders to do the copy,
  12022. // so the type/block size must be a multiple of 4.
  12023. if (src0_type == src1_type &&
  12024. (!ggml_is_quantized(src0_type) || (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op))) &&
  12025. (ggml_type_size(src0_type) % 2) == 0) {
  12026. return true;
  12027. }
  12028. return false;
  12029. }
  12030. case GGML_OP_REPEAT:
  12031. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  12032. case GGML_OP_REPEAT_BACK:
  12033. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  12034. case GGML_OP_ROPE:
  12035. case GGML_OP_ROPE_BACK:
  12036. case GGML_OP_NONE:
  12037. case GGML_OP_RESHAPE:
  12038. case GGML_OP_VIEW:
  12039. case GGML_OP_PERMUTE:
  12040. case GGML_OP_TRANSPOSE:
  12041. case GGML_OP_RMS_NORM:
  12042. return true;
  12043. case GGML_OP_NORM:
  12044. case GGML_OP_GROUP_NORM:
  12045. case GGML_OP_L2_NORM:
  12046. return ggml_is_contiguous(op->src[0]);
  12047. case GGML_OP_ADD:
  12048. case GGML_OP_SUB:
  12049. case GGML_OP_MUL:
  12050. case GGML_OP_DIV:
  12051. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12052. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  12053. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12054. case GGML_OP_ADD_ID:
  12055. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  12056. op->type == GGML_TYPE_F32;
  12057. case GGML_OP_SILU_BACK:
  12058. case GGML_OP_RMS_NORM_BACK:
  12059. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12060. case GGML_OP_SQR:
  12061. case GGML_OP_SQRT:
  12062. case GGML_OP_SIN:
  12063. case GGML_OP_COS:
  12064. case GGML_OP_CLAMP:
  12065. return op->src[0]->type == GGML_TYPE_F32;
  12066. case GGML_OP_LEAKY_RELU:
  12067. case GGML_OP_OPT_STEP_ADAMW:
  12068. case GGML_OP_OPT_STEP_SGD:
  12069. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12070. case GGML_OP_LOG:
  12071. case GGML_OP_TRI:
  12072. case GGML_OP_DIAG:
  12073. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12074. op->type == op->src[0]->type;
  12075. case GGML_OP_ARGSORT:
  12076. {
  12077. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12078. return false;
  12079. }
  12080. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12081. auto device = ggml_vk_get_device(ctx->device);
  12082. // pipeline_argsort_large_f32 requires vulkan memory model.
  12083. if (device->vulkan_memory_model) {
  12084. return true;
  12085. } else {
  12086. return op->ne[0] <= (1 << device->max_workgroup_size_log2);
  12087. }
  12088. }
  12089. case GGML_OP_TOP_K:
  12090. {
  12091. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12092. return false;
  12093. }
  12094. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12095. auto device = ggml_vk_get_device(ctx->device);
  12096. // We could potentially support larger, using argsort to sort the
  12097. // whole thing. Not clear if this is needed.
  12098. uint32_t min_pipeline = (uint32_t)log2f(float(op->ne[0])) + 1;
  12099. if (min_pipeline >= num_topk_pipelines ||
  12100. !device->pipeline_topk_f32[min_pipeline]) {
  12101. return false;
  12102. }
  12103. }
  12104. return true;
  12105. case GGML_OP_UPSCALE:
  12106. return op->src[0]->type == GGML_TYPE_F32 && !(op->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS);
  12107. case GGML_OP_ACC:
  12108. return op->src[0]->type == GGML_TYPE_F32;
  12109. case GGML_OP_CONCAT:
  12110. return ggml_type_size(op->src[0]->type) == ggml_type_size(GGML_TYPE_F32);
  12111. case GGML_OP_ADD1:
  12112. return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32)
  12113. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32)
  12114. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16);
  12115. case GGML_OP_ARANGE:
  12116. case GGML_OP_FILL:
  12117. return op->type == GGML_TYPE_F32;
  12118. case GGML_OP_SCALE:
  12119. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12120. case GGML_OP_PAD:
  12121. case GGML_OP_ROLL:
  12122. return op->src[0]->type == GGML_TYPE_F32;
  12123. case GGML_OP_DIAG_MASK_INF:
  12124. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12125. case GGML_OP_SOFT_MAX:
  12126. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12127. && (!op->src[1] || (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16));
  12128. case GGML_OP_SOFT_MAX_BACK:
  12129. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12130. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32;
  12131. case GGML_OP_SUM:
  12132. case GGML_OP_SUM_ROWS:
  12133. case GGML_OP_MEAN:
  12134. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12135. case GGML_OP_CUMSUM:
  12136. {
  12137. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12138. auto device = ggml_vk_get_device(ctx->device);
  12139. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  12140. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12141. }
  12142. return false;
  12143. }
  12144. case GGML_OP_SOLVE_TRI:
  12145. {
  12146. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12147. const vk_device& device = ggml_vk_get_device(ctx->device);
  12148. if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32) {
  12149. return false;
  12150. }
  12151. const uint32_t N = op->src[0]->ne[0];
  12152. const uint32_t K = op->src[1]->ne[0];
  12153. // K dimension limited to workgroup size
  12154. if (K > 1u << device->max_workgroup_size_log2) {
  12155. return false;
  12156. }
  12157. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((N + K) * sizeof(float));
  12158. if (batch_N == 0) {
  12159. return false;
  12160. }
  12161. return true;
  12162. }
  12163. case GGML_OP_ARGMAX:
  12164. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12165. case GGML_OP_COUNT_EQUAL:
  12166. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_I32
  12167. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_I32;
  12168. case GGML_OP_IM2COL:
  12169. return ggml_is_contiguous(op->src[1])
  12170. && op->src[1]->type == GGML_TYPE_F32
  12171. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12172. case GGML_OP_IM2COL_3D:
  12173. return op->src[1]->type == GGML_TYPE_F32
  12174. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12175. case GGML_OP_TIMESTEP_EMBEDDING:
  12176. return op->src[0]->type == GGML_TYPE_F32;
  12177. case GGML_OP_CONV_2D_DW:
  12178. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16)
  12179. && op->src[1]->type == GGML_TYPE_F32;
  12180. case GGML_OP_POOL_2D:
  12181. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12182. case GGML_OP_RWKV_WKV6:
  12183. case GGML_OP_RWKV_WKV7:
  12184. return true; // all inputs are contiguous, see ggml.c
  12185. case GGML_OP_SSM_SCAN:
  12186. {
  12187. for (int i = 0; i < 6; i++) {
  12188. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  12189. return false;
  12190. }
  12191. }
  12192. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  12193. return false;
  12194. }
  12195. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  12196. return false;
  12197. }
  12198. const uint32_t d_state = op->src[0]->ne[0];
  12199. const uint32_t head_dim = op->src[0]->ne[1];
  12200. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  12201. if (!is_mamba2) {
  12202. return false;
  12203. }
  12204. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  12205. return false;
  12206. }
  12207. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12208. const vk_device& device = ggml_vk_get_device(ctx->device);
  12209. const uint32_t SPLIT_H = 16;
  12210. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  12211. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  12212. return false;
  12213. }
  12214. return true;
  12215. }
  12216. case GGML_OP_SSM_CONV:
  12217. return op->src[0]->type == GGML_TYPE_F32;
  12218. case GGML_OP_CONV_TRANSPOSE_1D:
  12219. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  12220. case GGML_OP_CONV_2D:
  12221. case GGML_OP_CONV_TRANSPOSE_2D:
  12222. {
  12223. // Channel-contiguous format is not supported yet.
  12224. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12225. op->src[1]->type == GGML_TYPE_F32 &&
  12226. op->type == GGML_TYPE_F32 &&
  12227. ggml_is_contiguous(op->src[0]) &&
  12228. ggml_is_contiguous(op->src[1]) &&
  12229. ggml_is_contiguous(op));
  12230. }
  12231. default:
  12232. return false;
  12233. }
  12234. UNUSED(dev);
  12235. }
  12236. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  12237. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  12238. return false;
  12239. }
  12240. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12241. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  12242. return buft_ctx->device->idx == ctx->device;
  12243. }
  12244. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12245. const int min_batch_size = 32;
  12246. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  12247. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  12248. UNUSED(dev);
  12249. }
  12250. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  12251. /* .get_name = */ ggml_backend_vk_device_get_name,
  12252. /* .get_description = */ ggml_backend_vk_device_get_description,
  12253. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  12254. /* .get_type = */ ggml_backend_vk_device_get_type,
  12255. /* .get_props = */ ggml_backend_vk_device_get_props,
  12256. /* .init_backend = */ ggml_backend_vk_device_init,
  12257. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  12258. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  12259. /* .buffer_from_host_ptr = */ NULL,
  12260. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  12261. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  12262. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  12263. /* .event_new = */ NULL,
  12264. /* .event_free = */ NULL,
  12265. /* .event_synchronize = */ NULL,
  12266. };
  12267. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  12268. UNUSED(reg);
  12269. return GGML_VK_NAME;
  12270. }
  12271. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  12272. UNUSED(reg);
  12273. return ggml_backend_vk_get_device_count();
  12274. }
  12275. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  12276. static std::vector<ggml_backend_dev_t> devices;
  12277. static bool initialized = false;
  12278. {
  12279. static std::mutex mutex;
  12280. std::lock_guard<std::mutex> lock(mutex);
  12281. if (!initialized) {
  12282. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  12283. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  12284. char desc[256];
  12285. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  12286. ctx->device = i;
  12287. ctx->name = GGML_VK_NAME + std::to_string(i);
  12288. ctx->description = desc;
  12289. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  12290. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  12291. devices.push_back(new ggml_backend_device {
  12292. /* .iface = */ ggml_backend_vk_device_i,
  12293. /* .reg = */ reg,
  12294. /* .context = */ ctx,
  12295. });
  12296. }
  12297. initialized = true;
  12298. }
  12299. }
  12300. GGML_ASSERT(device < devices.size());
  12301. return devices[device];
  12302. }
  12303. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  12304. /* .get_name = */ ggml_backend_vk_reg_get_name,
  12305. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  12306. /* .get_device = */ ggml_backend_vk_reg_get_device,
  12307. /* .get_proc_address = */ NULL,
  12308. };
  12309. ggml_backend_reg_t ggml_backend_vk_reg() {
  12310. static ggml_backend_reg reg = {
  12311. /* .api_version = */ GGML_BACKEND_API_VERSION,
  12312. /* .iface = */ ggml_backend_vk_reg_i,
  12313. /* .context = */ nullptr,
  12314. };
  12315. try {
  12316. ggml_vk_instance_init();
  12317. return &reg;
  12318. } catch (const vk::SystemError& e) {
  12319. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  12320. return nullptr;
  12321. } catch (const std::exception &e) {
  12322. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  12323. return nullptr;
  12324. } catch (...) {
  12325. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  12326. return nullptr;
  12327. }
  12328. }
  12329. // Extension availability
  12330. static bool ggml_vk_instance_layer_settings_available() {
  12331. #ifdef GGML_VULKAN_VALIDATE
  12332. // Check if validation layer provides the extension
  12333. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  12334. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  12335. if (layer_name == layer.layerName.data()) {
  12336. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  12337. if (strcmp("VK_EXT_layer_settings", ext.extensionName.data()) == 0) {
  12338. return true;
  12339. }
  12340. }
  12341. }
  12342. }
  12343. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_layer_settings not found." << std::endl;
  12344. #endif
  12345. return false;
  12346. }
  12347. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  12348. #ifdef __APPLE__
  12349. // Check for portability enumeration extension for MoltenVK support
  12350. for (const auto& properties : instance_extensions) {
  12351. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  12352. return true;
  12353. }
  12354. }
  12355. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  12356. #endif
  12357. return false;
  12358. UNUSED(instance_extensions);
  12359. }
  12360. // Extension availability
  12361. static bool ggml_vk_instance_debug_utils_ext_available(
  12362. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  12363. // Check for portability enumeration extension for MoltenVK support
  12364. for (const auto & properties : instance_extensions) {
  12365. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  12366. return true;
  12367. }
  12368. }
  12369. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  12370. return false;
  12371. UNUSED(instance_extensions);
  12372. }
  12373. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  12374. VkPhysicalDeviceFeatures2 device_features2;
  12375. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  12376. VkPhysicalDeviceVulkan11Features vk11_features;
  12377. vk11_features.pNext = nullptr;
  12378. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  12379. device_features2.pNext = &vk11_features;
  12380. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  12381. return vk11_features.storageBuffer16BitAccess;
  12382. }
  12383. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  12384. switch (props.vendorID) {
  12385. case VK_VENDOR_ID_INTEL:
  12386. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  12387. // while some older hardware (ex. Arc A770) has performance regressions
  12388. return arch == vk_device_architecture::INTEL_XE2;
  12389. case VK_VENDOR_ID_AMD:
  12390. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  12391. // Workaround for AMD proprietary driver reporting support on all GPUs
  12392. return arch == vk_device_architecture::AMD_RDNA3;
  12393. }
  12394. return true;
  12395. default:
  12396. return true;
  12397. }
  12398. }
  12399. // checks
  12400. #ifdef GGML_VULKAN_CHECK_RESULTS
  12401. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  12402. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  12403. return;
  12404. }
  12405. for (int j = 0; j < level; j++) {
  12406. std::cerr << " ";
  12407. }
  12408. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  12409. done.push_back(tensor);
  12410. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12411. if (tensor->src[i] != nullptr) {
  12412. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  12413. }
  12414. }
  12415. }
  12416. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  12417. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  12418. return;
  12419. }
  12420. i0 = std::max(i0, 5);
  12421. i1 = std::max(i1, 5);
  12422. i2 = std::max(i2, 0);
  12423. i3 = std::max(i3, 0);
  12424. fprintf(stderr, " ");
  12425. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12426. fprintf(stderr, "%7d ", idx1);
  12427. }
  12428. fprintf(stderr, "\n");
  12429. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12430. fprintf(stderr, "%7d: ", idx0);
  12431. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12432. 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]) {
  12433. float val;
  12434. if (tensor->type == GGML_TYPE_F32) {
  12435. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12436. } else if (tensor->type == GGML_TYPE_F16) {
  12437. 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]));
  12438. } else if (tensor->type == GGML_TYPE_I32) {
  12439. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12440. } else {
  12441. GGML_ABORT("fatal error");
  12442. }
  12443. fprintf(stderr, "% 7.2f ", val);
  12444. } else {
  12445. fprintf(stderr, " ");
  12446. }
  12447. }
  12448. fprintf(stderr, "\n");
  12449. }
  12450. }
  12451. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  12452. void * tensor_data = tensor->data;
  12453. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  12454. if (is_gpu) {
  12455. const size_t tensor_size = ggml_nbytes(tensor);
  12456. tensor_data = malloc(tensor_size);
  12457. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12458. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  12459. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  12460. }
  12461. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  12462. 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;
  12463. if (tensor->src[0] != nullptr) {
  12464. 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;
  12465. }
  12466. if (tensor->src[1] != nullptr) {
  12467. 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;
  12468. }
  12469. std::cerr << std::endl << "Result:" << std::endl;
  12470. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12471. std::cerr << std::endl;
  12472. std::vector<const ggml_tensor *> done;
  12473. ggml_vk_print_graph_origin(tensor, done);
  12474. if (is_gpu) {
  12475. free(tensor_data);
  12476. }
  12477. }
  12478. void * comp_result;
  12479. size_t comp_size;
  12480. size_t comp_nb[GGML_MAX_DIMS];
  12481. size_t check_counter = 0;
  12482. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12483. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12484. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12485. return;
  12486. }
  12487. check_counter++;
  12488. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12489. return;
  12490. }
  12491. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12492. struct ggml_init_params iparams = {
  12493. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12494. /*.mem_buffer =*/ NULL,
  12495. /*.no_alloc =*/ false,
  12496. };
  12497. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12498. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12499. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12500. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  12501. std::vector<void *> cloned_mallocs;
  12502. struct ggml_tensor * tensor_clone = nullptr;
  12503. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  12504. tensor = cgraph->nodes[tensor_idx + f];
  12505. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12506. ggml_tensor * srci = tensor->src[i];
  12507. if (srci == nullptr) {
  12508. continue;
  12509. }
  12510. // If a src tensor has been cloned, use that one
  12511. auto it = cloned_tensors.find(srci);
  12512. if (it != cloned_tensors.end()) {
  12513. src_clone[i] = it->second;
  12514. continue;
  12515. }
  12516. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12517. size_t srci_size = ggml_nbytes(srci);
  12518. src_clone[i] = srci_clone;
  12519. void *src_buffer = malloc(srci_size);
  12520. cloned_mallocs.push_back(src_buffer);
  12521. srci_clone->data = src_buffer;
  12522. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12523. memcpy(srci_clone->data, srci->data, srci_size);
  12524. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12525. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12526. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12527. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12528. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12529. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12530. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12531. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12532. const int idx = i3*srci->ne[2] + i2;
  12533. ggml_vk_buffer_read(buffer_gpu, offset + idx * srci->nb[2], ((char *)srci_clone->data + idx * srci_clone->nb[2]), srci->ne[1] * srci->nb[1]);
  12534. }
  12535. }
  12536. srci_clone->nb[0] = srci->nb[0];
  12537. srci_clone->nb[1] = srci->nb[1];
  12538. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12539. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12540. }
  12541. } else {
  12542. if (offset + srci_size >= buffer_gpu->size) {
  12543. srci_size = buffer_gpu->size - offset;
  12544. }
  12545. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12546. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12547. }
  12548. } else {
  12549. GGML_ABORT("fatal error");
  12550. }
  12551. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12552. ggml_vk_print_tensor(srci, srci_name[i]);
  12553. }
  12554. }
  12555. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12556. const float * params = (const float *)tensor->op_params;
  12557. tensor_clone = ggml_flash_attn_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3], params[0], params[1], params[2]);
  12558. if (src_clone[4]) {
  12559. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12560. }
  12561. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12562. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12563. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12564. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12565. } else if (tensor->op == GGML_OP_SUB) {
  12566. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12567. } else if (tensor->op == GGML_OP_MUL) {
  12568. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12569. } else if (tensor->op == GGML_OP_DIV) {
  12570. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12571. } else if (tensor->op == GGML_OP_CONCAT) {
  12572. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12573. } else if (tensor->op == GGML_OP_UPSCALE) {
  12574. tensor_clone = ggml_interpolate(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], (ggml_scale_mode) tensor->op_params[0]);
  12575. } else if (tensor->op == GGML_OP_SCALE) {
  12576. const float * params = (const float *)tensor->op_params;
  12577. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12578. } else if (tensor->op == GGML_OP_ADD1) {
  12579. tensor_clone = ggml_add1(ggml_ctx, src_clone[0], src_clone[1]);
  12580. } else if (tensor->op == GGML_OP_ARANGE) {
  12581. const float start = ggml_get_op_params_f32(tensor, 0);
  12582. const float stop = ggml_get_op_params_f32(tensor, 1);
  12583. const float step = ggml_get_op_params_f32(tensor, 2);
  12584. tensor_clone = ggml_arange(ggml_ctx, start, stop, step);
  12585. } else if (tensor->op == GGML_OP_FILL) {
  12586. const float value = ggml_get_op_params_f32(tensor, 0);
  12587. tensor_clone = ggml_fill(ggml_ctx, tensor_clone, value);
  12588. } else if (tensor->op == GGML_OP_SQR) {
  12589. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12590. } else if (tensor->op == GGML_OP_SQRT) {
  12591. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12592. } else if (tensor->op == GGML_OP_SIN) {
  12593. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12594. } else if (tensor->op == GGML_OP_COS) {
  12595. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12596. } else if (tensor->op == GGML_OP_LOG) {
  12597. tensor_clone = ggml_log(ggml_ctx, src_clone[0]);
  12598. } else if (tensor->op == GGML_OP_TRI) {
  12599. tensor_clone = ggml_tri(ggml_ctx, src_clone[0], ggml_get_op_params_i32(tensor, 0));
  12600. } else if (tensor->op == GGML_OP_DIAG) {
  12601. tensor_clone = ggml_diag(ggml_ctx, src_clone[0]);
  12602. } else if (tensor->op == GGML_OP_CLAMP) {
  12603. const float * params = (const float *)tensor->op_params;
  12604. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12605. } else if (tensor->op == GGML_OP_PAD) {
  12606. tensor_clone = ggml_pad_ext(ggml_ctx, src_clone[0], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3],
  12607. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12608. } else if (tensor->op == GGML_OP_REPEAT) {
  12609. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12610. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12611. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12612. } else if (tensor->op == GGML_OP_ADD) {
  12613. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12614. } else if (tensor->op == GGML_OP_ACC) {
  12615. tensor_clone = ggml_acc(ggml_ctx, src_clone[0], src_clone[1], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3]);
  12616. } else if (tensor->op == GGML_OP_NORM) {
  12617. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12618. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12619. const float * float_params = (const float *)tensor->op_params;
  12620. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12621. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12622. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12623. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12624. const float eps = ((float *) tensor->op_params)[0];
  12625. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12626. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12627. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12628. } else if (tensor->op == GGML_OP_L2_NORM) {
  12629. const float eps = ((float *) tensor->op_params)[0];
  12630. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12631. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12632. if (tensor->src[1] != nullptr) {
  12633. const float * params = (const float *)tensor->op_params;
  12634. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12635. } else {
  12636. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12637. }
  12638. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12639. tensor_clone = ggml_soft_max_ext_back(ggml_ctx, src_clone[0], src_clone[1], ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  12640. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12641. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12642. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12643. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12644. const int mode = ((int32_t *) tensor->op_params)[2];
  12645. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12646. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12647. const float freq_base = ((float *) tensor->op_params)[5];
  12648. const float freq_scale = ((float *) tensor->op_params)[6];
  12649. const float ext_factor = ((float *) tensor->op_params)[7];
  12650. const float attn_factor = ((float *) tensor->op_params)[8];
  12651. const float beta_fast = ((float *) tensor->op_params)[9];
  12652. const float beta_slow = ((float *) tensor->op_params)[10];
  12653. if (mode & GGML_ROPE_TYPE_MROPE) {
  12654. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12655. if (tensor->op == GGML_OP_ROPE) {
  12656. tensor_clone = ggml_rope_multi(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, sections, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  12657. } else {
  12658. tensor_clone = ggml_rope_multi_back(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, sections, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  12659. }
  12660. } else {
  12661. if (tensor->op == GGML_OP_ROPE) {
  12662. tensor_clone = ggml_rope_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  12663. } else {
  12664. tensor_clone = ggml_rope_ext_back(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  12665. }
  12666. }
  12667. } else if (tensor->op == GGML_OP_UNARY) {
  12668. switch (ggml_get_unary_op(tensor)) {
  12669. case GGML_UNARY_OP_EXP:
  12670. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12671. break;
  12672. case GGML_UNARY_OP_SILU:
  12673. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12674. break;
  12675. case GGML_UNARY_OP_GELU:
  12676. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12677. break;
  12678. case GGML_UNARY_OP_GELU_ERF:
  12679. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12680. break;
  12681. case GGML_UNARY_OP_GELU_QUICK:
  12682. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12683. break;
  12684. case GGML_UNARY_OP_RELU:
  12685. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12686. break;
  12687. case GGML_UNARY_OP_NEG:
  12688. tensor_clone = ggml_neg(ggml_ctx, src_clone[0]);
  12689. break;
  12690. case GGML_UNARY_OP_TANH:
  12691. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12692. break;
  12693. case GGML_UNARY_OP_SIGMOID:
  12694. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12695. break;
  12696. case GGML_UNARY_OP_HARDSIGMOID:
  12697. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12698. break;
  12699. case GGML_UNARY_OP_HARDSWISH:
  12700. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12701. break;
  12702. case GGML_UNARY_OP_ABS:
  12703. tensor_clone = ggml_abs(ggml_ctx, src_clone[0]);
  12704. break;
  12705. case GGML_UNARY_OP_SOFTPLUS:
  12706. tensor_clone = ggml_softplus(ggml_ctx, src_clone[0]);
  12707. break;
  12708. case GGML_UNARY_OP_STEP:
  12709. tensor_clone = ggml_step(ggml_ctx, src_clone[0]);
  12710. break;
  12711. case GGML_UNARY_OP_ROUND:
  12712. tensor_clone = ggml_round(ggml_ctx, src_clone[0]);
  12713. break;
  12714. case GGML_UNARY_OP_CEIL:
  12715. tensor_clone = ggml_ceil(ggml_ctx, src_clone[0]);
  12716. break;
  12717. case GGML_UNARY_OP_FLOOR:
  12718. tensor_clone = ggml_floor(ggml_ctx, src_clone[0]);
  12719. break;
  12720. case GGML_UNARY_OP_TRUNC:
  12721. tensor_clone = ggml_trunc(ggml_ctx, src_clone[0]);
  12722. break;
  12723. default:
  12724. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12725. GGML_ABORT("fatal error");
  12726. }
  12727. } else if (tensor->op == GGML_OP_GLU) {
  12728. if (src_clone[1] == nullptr) {
  12729. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12730. } else {
  12731. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12732. }
  12733. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12734. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12735. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12736. if (tensor->src[1] == nullptr) {
  12737. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12738. tensor_clone->type = tensor->type;
  12739. } else {
  12740. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12741. }
  12742. } else if (tensor->op == GGML_OP_CONT) {
  12743. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12744. } else if (tensor->op == GGML_OP_RESHAPE) {
  12745. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12746. } else if (tensor->op == GGML_OP_VIEW) {
  12747. tensor_clone = ggml_view_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], tensor->nb[1], tensor->nb[2], tensor->nb[3], ((int32_t *) tensor->op_params)[0]);
  12748. } else if (tensor->op == GGML_OP_PERMUTE) {
  12749. int32_t * params = (int32_t *)tensor->op_params;
  12750. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12751. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12752. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12753. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12754. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12755. } else if (tensor->op == GGML_OP_ARGSORT) {
  12756. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12757. } else if (tensor->op == GGML_OP_TOP_K) {
  12758. tensor_clone = ggml_top_k(ggml_ctx, src_clone[0], tensor->ne[0]);
  12759. } else if (tensor->op == GGML_OP_SUM) {
  12760. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12761. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12762. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12763. } else if (tensor->op == GGML_OP_CUMSUM) {
  12764. tensor_clone = ggml_cumsum(ggml_ctx, src_clone[0]);
  12765. } else if (tensor->op == GGML_OP_MEAN) {
  12766. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  12767. } else if (tensor->op == GGML_OP_ARGMAX) {
  12768. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  12769. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  12770. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  12771. } else if (tensor->op == GGML_OP_SOLVE_TRI) {
  12772. tensor_clone = ggml_solve_tri(ggml_ctx, src_clone[0], src_clone[1], true, true, false);
  12773. } else if (tensor->op == GGML_OP_IM2COL) {
  12774. const int32_t s0 = tensor->op_params[0];
  12775. const int32_t s1 = tensor->op_params[1];
  12776. const int32_t p0 = tensor->op_params[2];
  12777. const int32_t p1 = tensor->op_params[3];
  12778. const int32_t d0 = tensor->op_params[4];
  12779. const int32_t d1 = tensor->op_params[5];
  12780. const bool is_2D = tensor->op_params[6] == 1;
  12781. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  12782. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  12783. const int32_t s0 = tensor->op_params[0];
  12784. const int32_t s1 = tensor->op_params[1];
  12785. const int32_t s2 = tensor->op_params[2];
  12786. const int32_t p0 = tensor->op_params[3];
  12787. const int32_t p1 = tensor->op_params[4];
  12788. const int32_t p2 = tensor->op_params[5];
  12789. const int32_t d0 = tensor->op_params[6];
  12790. const int32_t d1 = tensor->op_params[7];
  12791. const int32_t d2 = tensor->op_params[8];
  12792. const int32_t IC = tensor->op_params[9];
  12793. tensor_clone = ggml_im2col_3d(ggml_ctx, src_clone[0], src_clone[1], IC, s0, s1, s2, p0, p1, p2, d0, d1, d2, tensor->type);
  12794. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  12795. const int32_t dim = tensor->op_params[0];
  12796. const int32_t max_period = tensor->op_params[1];
  12797. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  12798. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  12799. const int32_t s0 = tensor->op_params[0];
  12800. const int32_t p0 = tensor->op_params[1];
  12801. const int32_t d0 = tensor->op_params[2];
  12802. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  12803. } else if (tensor->op == GGML_OP_POOL_2D) {
  12804. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  12805. const int32_t k0 = tensor->op_params[1];
  12806. const int32_t k1 = tensor->op_params[2];
  12807. const int32_t s0 = tensor->op_params[3];
  12808. const int32_t s1 = tensor->op_params[4];
  12809. const int32_t p0 = tensor->op_params[5];
  12810. const int32_t p1 = tensor->op_params[6];
  12811. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  12812. } else if (tensor->op == GGML_OP_CONV_2D) {
  12813. const int32_t s0 = tensor->op_params[0];
  12814. const int32_t s1 = tensor->op_params[1];
  12815. const int32_t p0 = tensor->op_params[2];
  12816. const int32_t p1 = tensor->op_params[3];
  12817. const int32_t d0 = tensor->op_params[4];
  12818. const int32_t d1 = tensor->op_params[5];
  12819. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12820. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  12821. const int32_t s0 = tensor->op_params[0];
  12822. const int32_t s1 = tensor->op_params[1];
  12823. const int32_t p0 = tensor->op_params[2];
  12824. const int32_t p1 = tensor->op_params[3];
  12825. const int32_t d0 = tensor->op_params[4];
  12826. const int32_t d1 = tensor->op_params[5];
  12827. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12828. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  12829. const int32_t s = tensor->op_params[0];
  12830. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  12831. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  12832. const float * op_params = (const float *)tensor->op_params;
  12833. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  12834. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  12835. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  12836. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  12837. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  12838. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  12839. src_clone[4], src_clone[5], src_clone[6]);
  12840. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  12841. src_clone[0]->flags = tensor->src[0]->flags;
  12842. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  12843. src_clone[2], src_clone[3], src_clone[4]);
  12844. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  12845. src_clone[0]->flags = tensor->src[0]->flags;
  12846. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  12847. src_clone[2]);
  12848. } else if (tensor->op == GGML_OP_ADD_ID) {
  12849. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12850. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  12851. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  12852. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  12853. } else if (tensor->op == GGML_OP_SSM_CONV) {
  12854. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  12855. } else if (tensor->op == GGML_OP_ROLL) {
  12856. const int32_t s0 = tensor->op_params[0];
  12857. const int32_t s1 = tensor->op_params[1];
  12858. const int32_t s2 = tensor->op_params[2];
  12859. const int32_t s3 = tensor->op_params[3];
  12860. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  12861. }
  12862. else {
  12863. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12864. GGML_ABORT("fatal error");
  12865. }
  12866. cloned_tensors[tensor] = tensor_clone;
  12867. }
  12868. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  12869. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  12870. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  12871. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12872. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  12873. }
  12874. comp_size = ggml_nbytes(tensor_clone);
  12875. comp_result = malloc(comp_size);
  12876. memcpy(comp_result, tensor_clone->data, comp_size);
  12877. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12878. for (auto m : cloned_mallocs) {
  12879. free(m);
  12880. }
  12881. ggml_free(ggml_ctx);
  12882. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  12883. }
  12884. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12885. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12886. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12887. return;
  12888. }
  12889. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12890. return;
  12891. }
  12892. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  12893. ggml_tensor * src0 = tensor->src[0];
  12894. ggml_tensor * src1 = tensor->src[1];
  12895. ggml_tensor * src2 = tensor->src[2];
  12896. ggml_tensor * src3 = tensor->src[3];
  12897. void * tensor_data = tensor->data;
  12898. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12899. size_t tensor_size = ggml_nbytes(tensor);
  12900. tensor_data = malloc(tensor_size);
  12901. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12902. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12903. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  12904. if (offset + tensor_size >= buffer_gpu->size) {
  12905. tensor_size = buffer_gpu->size - offset;
  12906. }
  12907. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  12908. }
  12909. float first_error_result = -1.0f;
  12910. float first_error_correct = -1.0f;
  12911. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  12912. double avg_err = 0.0;
  12913. size_t counter = 0;
  12914. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  12915. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  12916. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  12917. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  12918. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  12919. float correct = 0.0f;
  12920. float result = 0.0f;
  12921. if (buffer_size_fit) {
  12922. if (tensor->type == GGML_TYPE_F32) {
  12923. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12924. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12925. } else if (tensor->type == GGML_TYPE_F16) {
  12926. 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]));
  12927. 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]));
  12928. } else if (tensor->type == GGML_TYPE_BF16) {
  12929. correct = ggml_bf16_to_fp32(*(ggml_bf16_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]));
  12930. result = ggml_bf16_to_fp32(*(ggml_bf16_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]));
  12931. } else if (tensor->type == GGML_TYPE_I32) {
  12932. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12933. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12934. } else if (tensor->type == GGML_TYPE_I64) {
  12935. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12936. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12937. } else {
  12938. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  12939. }
  12940. } else {
  12941. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  12942. GGML_ABORT("fatal error");
  12943. }
  12944. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  12945. 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;
  12946. 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;
  12947. if (src0 != nullptr) {
  12948. 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;
  12949. }
  12950. if (src1 != nullptr) {
  12951. 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;
  12952. }
  12953. if (src2 != nullptr) {
  12954. 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;
  12955. }
  12956. if (src3 != nullptr) {
  12957. std::cerr << "src3=" << src3 << " src3->name=" << src3->name << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  12958. }
  12959. 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;
  12960. std::cerr << std::endl << "Result:" << std::endl;
  12961. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  12962. std::cerr << std::endl << "Correct:" << std::endl;
  12963. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  12964. std::cerr << std::endl;
  12965. std::vector<const ggml_tensor *> done;
  12966. ggml_vk_print_graph_origin(tensor, done);
  12967. GGML_ABORT("fatal error");
  12968. }
  12969. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  12970. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  12971. first_error[0] = i0;
  12972. first_error[1] = i1;
  12973. first_error[2] = i2;
  12974. first_error[3] = i3;
  12975. first_error_result = result;
  12976. first_error_correct = correct;
  12977. }
  12978. // Special case, value is infinite, avoid NaN result in avg_err
  12979. // NaN also appears in results, if both are nan error is 0
  12980. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  12981. avg_err += std::fabs(correct - result) / denom;
  12982. }
  12983. counter++;
  12984. }
  12985. }
  12986. }
  12987. }
  12988. avg_err /= counter;
  12989. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12990. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12991. 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;
  12992. if (src0 != nullptr) {
  12993. 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;
  12994. }
  12995. if (src1 != nullptr) {
  12996. 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;
  12997. }
  12998. if (src2 != nullptr) {
  12999. 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;
  13000. }
  13001. if (src3 != nullptr) {
  13002. std::cerr << "src3=" << src3 << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  13003. }
  13004. 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;
  13005. std::cerr << std::endl << "Result:" << std::endl;
  13006. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13007. std::cerr << std::endl << "Correct:" << std::endl;
  13008. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  13009. std::cerr << std::endl;
  13010. std::vector<const ggml_tensor *> done;
  13011. ggml_vk_print_graph_origin(tensor, done);
  13012. }
  13013. if (avg_err > 0.5 || std::isnan(avg_err)) {
  13014. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13015. 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;
  13016. if (src0 != nullptr) {
  13017. 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;
  13018. }
  13019. if (src1 != nullptr) {
  13020. 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;
  13021. }
  13022. if (src2 != nullptr) {
  13023. 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;
  13024. }
  13025. if (src3 != nullptr) {
  13026. std::cerr << "src3=" << src3 << " op=" << ggml_op_name(src3->op) << " type=" << ggml_type_name(src3->type) << " ne0=" << src3->ne[0] << " nb0=" << src3->nb[0] << " ne1=" << src3->ne[1] << " nb1=" << src3->nb[1] << " ne2=" << src3->ne[2] << " nb2=" << src3->nb[2] << " ne3=" << src3->ne[3] << " nb3=" << src3->nb[3] << " offset=" << src3->view_offs << std::endl;
  13027. }
  13028. 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;
  13029. std::cerr << std::endl << "Result:" << std::endl;
  13030. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  13031. std::cerr << std::endl << "Correct:" << std::endl;
  13032. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  13033. std::cerr << std::endl;
  13034. std::vector<const ggml_tensor *> done;
  13035. ggml_vk_print_graph_origin(tensor, done);
  13036. GGML_ABORT("fatal error");
  13037. } else {
  13038. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  13039. }
  13040. free(comp_result);
  13041. comp_result = nullptr;
  13042. comp_size = 0;
  13043. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13044. free(tensor_data);
  13045. }
  13046. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  13047. }
  13048. #endif
  13049. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)