ggml-vulkan.cpp 801 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800
  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, bool small_cache, FaCodePath path, bool aligned, bool f32acc)
  319. : HSK(HSK), HSV(HSV), small_rows(small_rows), small_cache(small_cache), path(path), aligned(aligned), f32acc(f32acc) {}
  320. uint32_t HSK, HSV;
  321. bool small_rows, small_cache;
  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, small_cache, path, aligned, f32acc) <
  327. std::tie(b.HSK, b.HSV, b.small_rows, b.small_cache, 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_sigmoid_norm_bias{ GGML_OP_UNARY, GGML_OP_RESHAPE, GGML_OP_ADD,
  363. GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS,
  364. GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP,
  365. GGML_OP_DIV, GGML_OP_RESHAPE };
  366. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  367. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  368. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  369. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  370. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  371. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  372. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  373. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  374. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  375. //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 ]
  376. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  377. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  378. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  379. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  380. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  381. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  382. { 1, 0, 0 }, // reshape->src[0] == softmax
  383. { 2, 0, 0 }, // argsort->src[0] == softmax
  384. { 3, 0, 2 }, // view->src[0] == argsort
  385. { 4, 0, 1 }, // get_rows->src[0] == reshape
  386. { 4, 1, 3 }, // get_rows->src[1] == view
  387. { 5, 0, 4 }, // reshape->src[0] == get_rows
  388. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  389. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  390. { 8, 0, 5 }, // div->src[0] == reshape
  391. { 8, 1, 7 }, // div->src[1] == clamp
  392. { 9, 0, 8 }, // reshape->src[0] == div
  393. };
  394. //node #436 ( UNARY): ffn_moe_probs-10 ( 256K) [Vulka ] use=2: ffn_moe_logits-10 ( 256K) [Vulka ]
  395. //node #437 ( RESHAPE): ffn_moe_probs-10 (re ( 256K) [Vulka ] use=1: ffn_moe_probs-10 ( 256K) [Vulka ]
  396. //node #438 ( ADD): ffn_moe_probs_biased ( 256K) [Vulka ] use=1: ffn_moe_probs-10 ( 256K) [Vulka ] blk.10.exp_probs_b.b ( 0K) [Vulka ]
  397. //node #439 ( ARGSORT): ffn_moe_argsort-10 ( 256K) [Vulka ] use=1: ffn_moe_probs_biased ( 256K) [Vulka ]
  398. //node #440 ( VIEW): ffn_moe_topk-10 ( 255K) [Vulka ] use=3: ffn_moe_argsort-10 ( 256K) [Vulka ]
  399. //node #441 ( GET_ROWS): ffn_moe_weights-10 ( 12K) [Vulka ] use=1: ffn_moe_probs-10 (re ( 256K) [Vulka ] ffn_moe_topk-10 ( 255K) [Vulka ]
  400. //node #442 ( RESHAPE): ffn_moe_weights-10 ( ( 12K) [Vulka ] use=2: ffn_moe_weights-10 ( 12K) [Vulka ]
  401. //node #443 ( SUM_ROWS): ffn_moe_weights_sum- ( 2K) [Vulka ] use=1: ffn_moe_weights-10 ( ( 12K) [Vulka ]
  402. //node #444 ( CLAMP): ffn_moe_weights_sum_ ( 2K) [Vulka ] use=1: ffn_moe_weights_sum- ( 2K) [Vulka ]
  403. //node #445 ( DIV): ffn_moe_weights_norm ( 12K) [Vulka ] use=1: ffn_moe_weights-10 ( ( 12K) [Vulka ] ffn_moe_weights_sum_ ( 2K) [Vulka ]
  404. //node #446 ( RESHAPE): ffn_moe_weights_norm ( 12K) [Vulka ] use=1: ffn_moe_weights_norm ( 12K) [Vulka ]
  405. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_sigmoid_norm_bias_edges {
  406. { 1, 0, 0 }, // reshape->src[0] == sigmoid
  407. { 2, 0, 0 }, // add->src[0] == sigmoid
  408. { 3, 0, 2 }, // argsort->src[0] == add
  409. { 4, 0, 3 }, // view->src[0] == argsort
  410. { 5, 0, 1 }, // get_rows->src[0] == reshape
  411. { 5, 1, 4 }, // get_rows->src[1] == view
  412. { 6, 0, 5 }, // reshape->src[0] == get_rows
  413. { 7, 0, 6 }, // sum_rows->src[0] == reshape
  414. { 8, 0, 7 }, // clamp->src[0] == sum_rows
  415. { 9, 0, 6 }, // div->src[0] == reshape
  416. { 9, 1, 8 }, // div->src[1] == clamp
  417. {10, 0, 9 }, // reshape->src[0] == div
  418. };
  419. // same as early_softmax_norm but ending after the get_rows
  420. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  421. { 1, 0, 0 }, // reshape->src[0] == softmax
  422. { 2, 0, 0 }, // argsort->src[0] == softmax
  423. { 3, 0, 2 }, // view->src[0] == argsort
  424. { 4, 0, 1 }, // get_rows->src[0] == reshape
  425. { 4, 1, 3 }, // get_rows->src[1] == view
  426. };
  427. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  428. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  429. //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 ]
  430. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  431. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  432. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  433. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  434. { 1, 0, 0 }, // view->src[0] == argsort
  435. { 2, 1, 1 }, // get_rows->src[1] == view
  436. { 3, 0, 2 }, // reshape->src[0] == get_rows
  437. { 4, 0, 3 }, // soft_max->src[0] == reshape
  438. { 5, 0, 4 }, // reshape->src[0] == soft_max
  439. };
  440. enum topk_moe_mode {
  441. TOPK_MOE_EARLY_SOFTMAX,
  442. TOPK_MOE_EARLY_SOFTMAX_NORM,
  443. TOPK_MOE_LATE_SOFTMAX,
  444. TOPK_MOE_SIGMOID_NORM_BIAS,
  445. TOPK_MOE_COUNT,
  446. };
  447. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  448. { 1, 0, 0 }, // view->src[0] == rope
  449. { 2, 0, 1 }, // set_rows->src[0] == view
  450. };
  451. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  452. { 1, 0, 0 }, // mul->src[0] == rms
  453. { 2, 0, 1 }, // rope->src[0] == mul
  454. { 3, 0, 2 }, // view->src[0] == rope
  455. { 4, 0, 3 }, // set_rows->src[0] == view
  456. };
  457. struct vk_device_struct {
  458. std::recursive_mutex mutex;
  459. vk::PhysicalDevice physical_device;
  460. vk::PhysicalDeviceProperties properties;
  461. std::string name;
  462. uint64_t max_memory_allocation_size;
  463. uint64_t max_buffer_size;
  464. uint64_t suballocation_block_size;
  465. uint64_t min_imported_host_pointer_alignment;
  466. bool external_memory_host {};
  467. bool fp16;
  468. bool bf16;
  469. bool pipeline_robustness;
  470. bool memory_priority;
  471. vk::Device device;
  472. uint32_t vendor_id;
  473. vk::DriverId driver_id;
  474. vk_device_architecture architecture;
  475. vk_queue compute_queue;
  476. vk_queue transfer_queue;
  477. bool single_queue;
  478. bool support_async;
  479. uint32_t subgroup_size;
  480. uint32_t subgroup_size_log2;
  481. uint32_t shader_core_count;
  482. bool uma;
  483. bool prefer_host_memory;
  484. bool float_controls_rte_fp16;
  485. bool subgroup_arithmetic;
  486. bool subgroup_shuffle;
  487. bool subgroup_ballot;
  488. bool subgroup_clustered;
  489. bool subgroup_vote;
  490. bool multi_add;
  491. bool shader_int64;
  492. bool buffer_device_address;
  493. bool vulkan_memory_model;
  494. bool add_rms_fusion;
  495. uint32_t partials_binding_alignment;
  496. bool integer_dot_product;
  497. // 0: default, 1: force mmvq, -1: disable mmvq
  498. int32_t mmvq_mode;
  499. bool subgroup_size_control;
  500. uint32_t subgroup_min_size;
  501. uint32_t subgroup_max_size;
  502. bool subgroup_require_full_support;
  503. // floor(log2(maxComputeWorkGroupInvocations))
  504. uint32_t max_workgroup_size_log2 {};
  505. bool coopmat_support;
  506. bool coopmat_acc_f32_support {};
  507. bool coopmat_acc_f16_support {};
  508. bool coopmat_bf16_support {};
  509. bool coopmat_support_16x16x16_f16acc {};
  510. bool coopmat_support_16x16x16_f32acc {};
  511. bool coopmat1_fa_support {};
  512. uint32_t coopmat_m;
  513. uint32_t coopmat_n;
  514. uint32_t coopmat_k;
  515. bool coopmat_int_support;
  516. uint32_t coopmat_int_m;
  517. uint32_t coopmat_int_n;
  518. uint32_t coopmat_int_k;
  519. bool coopmat2;
  520. bool pipeline_executable_properties_support {};
  521. size_t idx;
  522. bool mul_mat_l[GGML_TYPE_COUNT];
  523. bool mul_mat_m[GGML_TYPE_COUNT];
  524. bool mul_mat_s[GGML_TYPE_COUNT];
  525. bool mul_mat_id_l[GGML_TYPE_COUNT];
  526. bool mul_mat_id_m[GGML_TYPE_COUNT];
  527. bool mul_mat_id_s[GGML_TYPE_COUNT];
  528. vk::DescriptorSetLayout dsl;
  529. vk_matmul_pipeline pipeline_matmul_f32 {};
  530. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  531. vk_matmul_pipeline pipeline_matmul_bf16 {};
  532. vk_matmul_pipeline2 pipeline_matmul_f16;
  533. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  534. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  535. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  536. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  537. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  538. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  539. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  540. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  541. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  542. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  543. vk_pipeline pipeline_matmul_split_k_reduce;
  544. vk_pipeline pipeline_quantize_q8_1_x4;
  545. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  546. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  547. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  548. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  549. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  550. vk_pipeline pipeline_dequant_mul_mat_vec_id_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  551. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  552. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  553. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  554. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  555. vk_pipeline pipeline_acc_f32;
  556. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  557. vk_pipeline pipeline_add[2][2][2];
  558. vk_pipeline pipeline_add_norepeat[2][2][2];
  559. vk_pipeline pipeline_sub[2][2][2];
  560. vk_pipeline pipeline_sub_norepeat[2][2][2];
  561. vk_pipeline pipeline_mul[2][2][2];
  562. vk_pipeline pipeline_mul_norepeat[2][2][2];
  563. vk_pipeline pipeline_div[2][2][2];
  564. vk_pipeline pipeline_div_norepeat[2][2][2];
  565. vk_pipeline pipeline_add_rms[2][2][2];
  566. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  567. // indexed by num_additional_fused_ops == num_adds - 1
  568. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  569. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  570. vk_pipeline pipeline_add_id_f32;
  571. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  572. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32, pipeline_upscale_bilinear_antialias_f32;
  573. vk_pipeline pipeline_scale_f32;
  574. vk_pipeline pipeline_sqr_f32;
  575. vk_pipeline pipeline_sqrt_f32;
  576. vk_pipeline pipeline_sin_f32;
  577. vk_pipeline pipeline_cos_f32;
  578. vk_pipeline pipeline_log[2];
  579. vk_pipeline pipeline_tri[2];
  580. vk_pipeline pipeline_diag[2];
  581. vk_pipeline pipeline_clamp_f32;
  582. vk_pipeline pipeline_pad_f32;
  583. vk_pipeline pipeline_roll_f32;
  584. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  585. 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;
  586. 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;
  587. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  588. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  589. vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
  590. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  591. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  592. vk_pipeline pipeline_norm_f32;
  593. vk_pipeline pipeline_group_norm_f32;
  594. vk_pipeline pipeline_rms_norm_f32;
  595. vk_pipeline pipeline_rms_norm_mul_f32;
  596. vk_pipeline pipeline_rms_norm_partials_f32;
  597. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  598. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  599. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  600. vk_pipeline pipeline_rms_norm_back_f32;
  601. vk_pipeline pipeline_l2_norm_f32;
  602. // [src/dst 0=fp32,1=fp16]
  603. vk_pipeline pipeline_exp[2];
  604. vk_pipeline pipeline_gelu[2];
  605. vk_pipeline pipeline_gelu_erf[2];
  606. vk_pipeline pipeline_gelu_quick[2];
  607. vk_pipeline pipeline_silu[2];
  608. vk_pipeline pipeline_relu[2];
  609. vk_pipeline pipeline_xielu[2];
  610. vk_pipeline pipeline_neg[2];
  611. vk_pipeline pipeline_tanh[2];
  612. vk_pipeline pipeline_sigmoid[2];
  613. vk_pipeline pipeline_hardsigmoid[2];
  614. vk_pipeline pipeline_hardswish[2];
  615. vk_pipeline pipeline_abs[2];
  616. vk_pipeline pipeline_softplus[2];
  617. vk_pipeline pipeline_step[2];
  618. vk_pipeline pipeline_round[2];
  619. vk_pipeline pipeline_ceil[2];
  620. vk_pipeline pipeline_floor[2];
  621. vk_pipeline pipeline_trunc[2];
  622. vk_pipeline pipeline_add1_f16_f16;
  623. vk_pipeline pipeline_add1_f16_f32;
  624. vk_pipeline pipeline_add1_f32_f32;
  625. vk_pipeline pipeline_arange_f32;
  626. vk_pipeline pipeline_fill_f32;
  627. vk_pipeline pipeline_geglu[2];
  628. vk_pipeline pipeline_reglu[2];
  629. vk_pipeline pipeline_swiglu[2];
  630. vk_pipeline pipeline_swiglu_oai[2];
  631. vk_pipeline pipeline_geglu_erf[2];
  632. vk_pipeline pipeline_geglu_quick[2];
  633. vk_pipeline pipeline_leaky_relu_f32;
  634. vk_pipeline pipeline_silu_back_f32;
  635. vk_pipeline pipeline_diag_mask_inf_f32;
  636. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  637. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  638. vk_pipeline pipeline_soft_max_back_f32;
  639. vk_pipeline pipeline_soft_max_large1_f32, pipeline_soft_max_large1_f32_f16;
  640. vk_pipeline pipeline_soft_max_large2_f32, pipeline_soft_max_large2_f32_f16;
  641. vk_pipeline pipeline_soft_max_large3_f32, pipeline_soft_max_large3_f32_f16;
  642. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  643. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  644. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16, pipeline_rope_multi_f32_f16;
  645. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  646. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  647. vk_pipeline pipeline_argsort_large_f32[num_argsort_pipelines];
  648. vk_pipeline pipeline_topk_f32[num_topk_pipelines];
  649. vk_pipeline pipeline_sum_rows_f32;
  650. vk_pipeline pipeline_cumsum_f32;
  651. vk_pipeline pipeline_cumsum_small_f32;
  652. vk_pipeline pipeline_cumsum_multipass1_f32;
  653. vk_pipeline pipeline_cumsum_multipass2_f32;
  654. vk_pipeline pipeline_argmax_f32;
  655. vk_pipeline pipeline_count_equal_i32;
  656. std::map<vk_solve_tri_pipeline_state, vk_pipeline> pipeline_solve_tri_f32;
  657. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  658. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  659. vk_pipeline pipeline_timestep_embedding_f32;
  660. vk_pipeline pipeline_conv_transpose_1d_f32;
  661. vk_pipeline pipeline_pool2d_f32;
  662. vk_pipeline pipeline_rwkv_wkv6_f32;
  663. vk_pipeline pipeline_rwkv_wkv7_f32;
  664. vk_pipeline pipeline_ssm_scan_f32_d128;
  665. vk_pipeline pipeline_ssm_scan_f32_d256;
  666. vk_pipeline pipeline_ssm_conv_f32;
  667. vk_pipeline pipeline_opt_step_adamw_f32;
  668. vk_pipeline pipeline_opt_step_sgd_f32;
  669. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  670. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  671. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  672. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  673. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  674. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  675. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  676. vk_pipeline pipeline_flash_attn_split_k_reduce;
  677. vk_pipeline pipeline_count_experts;
  678. // [2] is for whether to take n_experts from spec constant (0) or push constant (1)
  679. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][2];
  680. std::vector<vk_pipeline_ref> all_pipelines;
  681. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  682. vk::Fence fence;
  683. vk_buffer sync_staging;
  684. ggml_backend_buffer_type buffer_type;
  685. bool disable_fusion;
  686. bool disable_host_visible_vidmem;
  687. bool allow_sysmem_fallback;
  688. bool disable_graph_optimize;
  689. #ifdef GGML_VULKAN_MEMORY_DEBUG
  690. std::unique_ptr<vk_memory_logger> memory_logger;
  691. #endif
  692. ~vk_device_struct() {
  693. VK_LOG_DEBUG("destroy device " << name);
  694. device.destroyFence(fence);
  695. ggml_vk_destroy_buffer(sync_staging);
  696. compute_queue.cmd_pool.destroy(device);
  697. transfer_queue.cmd_pool.destroy(device);
  698. for (auto& pipeline : all_pipelines) {
  699. if (pipeline.expired()) {
  700. continue;
  701. }
  702. vk_pipeline pl = pipeline.lock();
  703. ggml_vk_destroy_pipeline(device, pl);
  704. }
  705. all_pipelines.clear();
  706. device.destroyDescriptorSetLayout(dsl);
  707. device.destroy();
  708. }
  709. };
  710. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  711. cmd_buffer_idx = 0;
  712. q = q_;
  713. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  714. pool = device->device.createCommandPool(command_pool_create_info);
  715. }
  716. void vk_command_pool::destroy(vk::Device& device) {
  717. device.destroyCommandPool(pool);
  718. pool = nullptr;
  719. cmd_buffers.clear();
  720. }
  721. struct vk_buffer_struct {
  722. vk::Buffer buffer = VK_NULL_HANDLE;
  723. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  724. vk::MemoryPropertyFlags memory_property_flags;
  725. void * ptr;
  726. size_t size = 0;
  727. vk::DeviceAddress bda_addr {};
  728. vk_device device;
  729. ~vk_buffer_struct() {
  730. if (size == 0) {
  731. return;
  732. }
  733. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  734. device->device.freeMemory(device_memory);
  735. device->device.destroyBuffer(buffer);
  736. }
  737. };
  738. struct vk_subbuffer {
  739. vk_buffer buffer;
  740. uint64_t offset;
  741. uint64_t size;
  742. operator vk::DescriptorBufferInfo() const {
  743. return { buffer->buffer, offset, size };
  744. }
  745. };
  746. // vk_event is used for the event-related backend interfaces. It uses 'event' for
  747. // event_wait and 'fence' for event_synchronize. Polling on an event for
  748. // event_synchronize wouldn't be sufficient to wait for command buffers to complete,
  749. // and would lead to validation errors.
  750. struct vk_event {
  751. vk::Event event;
  752. vk::Fence fence;
  753. };
  754. struct vk_semaphore {
  755. vk::Semaphore s;
  756. uint64_t value;
  757. };
  758. struct vk_submission {
  759. vk::CommandBuffer buffer;
  760. std::vector<vk_semaphore> wait_semaphores;
  761. std::vector<vk_semaphore> signal_semaphores;
  762. };
  763. typedef std::vector<vk_submission> vk_sequence;
  764. struct vk_mat_mat_push_constants {
  765. uint32_t M; uint32_t N; uint32_t K;
  766. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  767. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  768. uint32_t k_split;
  769. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  770. uint32_t padded_N;
  771. };
  772. #define MAT_VEC_FUSION_FLAGS_BIAS0 0x1
  773. #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
  774. #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
  775. #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
  776. struct vk_mat_vec_push_constants {
  777. uint32_t ncols;
  778. uint32_t stride_a;
  779. uint32_t stride_b;
  780. uint32_t stride_d;
  781. uint32_t batch_stride_a;
  782. uint32_t batch_stride_b;
  783. uint32_t batch_stride_d;
  784. uint32_t fusion_flags;
  785. uint32_t ne02;
  786. uint32_t ne12;
  787. uint32_t broadcast2;
  788. uint32_t broadcast3;
  789. };
  790. struct vk_mat_vec_p021_push_constants {
  791. uint32_t ncols_x;
  792. uint32_t nrows_x;
  793. uint32_t nchannels_x;
  794. uint32_t nchannels_y;
  795. uint32_t b_offset;
  796. uint32_t d_offset;
  797. uint32_t fusion_flags;
  798. };
  799. struct vk_mat_vec_nc_push_constants {
  800. uint32_t ncols_x;
  801. uint32_t nrows_x;
  802. uint32_t row_stride_x;
  803. uint32_t channel_stride_x;
  804. uint32_t channel_stride_y;
  805. uint32_t channel_x_divisor;
  806. uint32_t ne12;
  807. uint32_t b_offset;
  808. uint32_t d_offset;
  809. uint32_t nb03;
  810. uint32_t nb13;
  811. uint32_t nb23;
  812. uint32_t fusion_flags;
  813. };
  814. struct vk_mat_mat_id_push_constants {
  815. uint32_t M; uint32_t N; uint32_t K;
  816. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  817. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  818. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  819. uint32_t padded_N;
  820. };
  821. struct vk_mat_vec_id_push_constants {
  822. uint32_t ncols;
  823. uint32_t stride_a;
  824. uint32_t stride_b;
  825. uint32_t stride_d;
  826. uint32_t batch_stride_a;
  827. uint32_t batch_stride_b;
  828. uint32_t batch_stride_d;
  829. uint32_t fusion_flags;
  830. uint32_t nei0;
  831. uint32_t ne11;
  832. };
  833. struct vk_flash_attn_push_constants {
  834. uint32_t N;
  835. uint32_t KV;
  836. uint32_t ne1;
  837. uint32_t ne2;
  838. uint32_t ne3;
  839. uint32_t neq2;
  840. uint32_t neq3;
  841. uint32_t nek2;
  842. uint32_t nek3;
  843. uint32_t nev2;
  844. uint32_t nev3;
  845. uint32_t nem1;
  846. uint32_t nem2;
  847. uint32_t nem3;
  848. uint32_t nb01;
  849. uint32_t nb02;
  850. uint32_t nb03;
  851. uint32_t nb11;
  852. uint32_t nb12;
  853. uint32_t nb13;
  854. uint32_t nb21;
  855. uint32_t nb22;
  856. uint32_t nb23;
  857. float scale;
  858. float max_bias;
  859. float logit_softcap;
  860. uint32_t mask_n_head_log2;
  861. float m0;
  862. float m1;
  863. uint32_t gqa_ratio;
  864. uint32_t split_kv;
  865. uint32_t k_num;
  866. };
  867. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  868. struct vk_op_push_constants {
  869. uint32_t KX;
  870. uint32_t KY;
  871. float param1;
  872. float param2;
  873. float param3;
  874. float param4;
  875. };
  876. struct vk_op_count_experts_push_constants {
  877. uint32_t ne00;
  878. uint32_t ne01;
  879. uint32_t nb00;
  880. uint32_t nb01;
  881. uint32_t a_offset;
  882. };
  883. struct vk_op_glu_push_constants {
  884. uint32_t N;
  885. uint32_t ne00;
  886. uint32_t ne20;
  887. uint32_t mode; // 0: default, 1: swapped, 2: split
  888. float alpha; // for swiglu_oai
  889. float limit;
  890. };
  891. struct vk_op_unary_push_constants {
  892. uint32_t ne;
  893. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  894. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  895. uint32_t misalign_offsets;
  896. float param1; float param2;
  897. uint32_t ne0_012mp; uint32_t ne0_012L;
  898. uint32_t ne0_01mp; uint32_t ne0_01L;
  899. uint32_t ne0_0mp; uint32_t ne0_0L;
  900. uint32_t ne1_012mp; uint32_t ne1_012L;
  901. uint32_t ne1_01mp; uint32_t ne1_01L;
  902. uint32_t ne1_0mp; uint32_t ne1_0L;
  903. };
  904. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  905. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  906. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  907. ne = ne != 0 ? ne : ggml_nelements(dst);
  908. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  909. vk_op_unary_push_constants p{};
  910. p.ne = (uint32_t)ne;
  911. size_t src0_tsize = ggml_type_size(src0->type);
  912. p.ne00 = (uint32_t)src0->ne[0];
  913. p.ne01 = (uint32_t)src0->ne[1];
  914. p.ne02 = (uint32_t)src0->ne[2];
  915. p.ne03 = (uint32_t)src0->ne[3];
  916. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  917. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  918. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  919. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  920. size_t dst_tsize = ggml_type_size(dst->type);
  921. p.ne10 = (uint32_t)dst->ne[0];
  922. p.ne11 = (uint32_t)dst->ne[1];
  923. p.ne12 = (uint32_t)dst->ne[2];
  924. p.ne13 = (uint32_t)dst->ne[3];
  925. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  926. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  927. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  928. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  929. return p; // offsets are initialized later in ggml_vk_op
  930. }
  931. struct vk_op_pad_push_constants {
  932. uint32_t ne;
  933. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  934. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  935. uint32_t misalign_offsets;
  936. uint32_t circular;
  937. uint32_t lp0; uint32_t rp0;
  938. uint32_t lp1; uint32_t rp1;
  939. uint32_t lp2; uint32_t rp2;
  940. uint32_t lp3; uint32_t rp3;
  941. };
  942. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  943. int64_t ne = ggml_nelements(dst);
  944. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  945. vk_op_pad_push_constants p{};
  946. p.ne = (uint32_t)ne;
  947. size_t src0_tsize = ggml_type_size(src0->type);
  948. p.ne00 = (uint32_t)src0->ne[0];
  949. p.ne01 = (uint32_t)src0->ne[1];
  950. p.ne02 = (uint32_t)src0->ne[2];
  951. p.ne03 = (uint32_t)src0->ne[3];
  952. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  953. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  954. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  955. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  956. size_t dst_tsize = ggml_type_size(dst->type);
  957. p.ne10 = (uint32_t)dst->ne[0];
  958. p.ne11 = (uint32_t)dst->ne[1];
  959. p.ne12 = (uint32_t)dst->ne[2];
  960. p.ne13 = (uint32_t)dst->ne[3];
  961. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  962. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  963. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  964. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  965. p.lp0 = dst->op_params[0];
  966. p.rp0 = dst->op_params[1];
  967. p.lp1 = dst->op_params[2];
  968. p.rp1 = dst->op_params[3];
  969. p.lp2 = dst->op_params[4];
  970. p.rp2 = dst->op_params[5];
  971. p.lp3 = dst->op_params[6];
  972. p.rp3 = dst->op_params[7];
  973. p.circular = dst->op_params[8];
  974. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  975. }
  976. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  977. // Precompute mp (m' in the paper) and L such that division
  978. // can be computed using a multiply (high 32b of 64b result)
  979. // and a shift:
  980. //
  981. // n/d = (mulhi(n, mp) + n) >> L;
  982. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  983. {
  984. // compute L = ceil(log2(d));
  985. L = 0;
  986. while (L < 32 && (uint32_t{1} << L) < d) {
  987. L++;
  988. }
  989. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  990. }
  991. template <typename T> void init_pushconst_fastdiv(T &p) {
  992. GGML_UNUSED(p);
  993. static_assert(!std::is_const<T>::value, "unexpected type");
  994. }
  995. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  996. // Compute magic values to divide by these six numbers.
  997. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  998. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  999. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  1000. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  1001. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  1002. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  1003. }
  1004. struct vk_op_binary_push_constants {
  1005. uint32_t ne;
  1006. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1007. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  1008. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  1009. uint32_t misalign_offsets;
  1010. float param1; float param2; int32_t param3;
  1011. };
  1012. struct vk_op_multi_add_push_constants {
  1013. // shape for dst
  1014. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  1015. // strides for srcs+dst
  1016. uint32_t nb[MAX_PARAMETER_COUNT][4];
  1017. uint32_t rms_partials;
  1018. };
  1019. // update multi_add.comp if this changes
  1020. static_assert(MAX_PARAMETER_COUNT == 12);
  1021. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  1022. struct vk_op_topk_moe_push_constants {
  1023. uint32_t n_rows;
  1024. uint32_t n_experts_push;
  1025. uint32_t n_expert_used;
  1026. float clamp_min;
  1027. float clamp_max;
  1028. uint32_t gating_func;
  1029. uint32_t has_bias;
  1030. uint32_t with_norm;
  1031. float output_scale;
  1032. float output_bias;
  1033. };
  1034. struct vk_op_add_id_push_constants {
  1035. uint32_t ne0;
  1036. uint32_t ne1;
  1037. uint32_t s01;
  1038. uint32_t s02;
  1039. uint32_t s11;
  1040. uint32_t s21;
  1041. };
  1042. struct vk_op_diag_mask_push_constants {
  1043. uint32_t ncols;
  1044. uint32_t rows_per_channel;
  1045. int32_t n_past;
  1046. };
  1047. struct vk_op_rope_push_constants {
  1048. uint32_t rope_mode;
  1049. uint32_t ncols;
  1050. uint32_t nrows;
  1051. uint32_t n_dims;
  1052. float freq_scale;
  1053. uint32_t p_delta_rows;
  1054. float freq_base;
  1055. float ext_factor;
  1056. float attn_factor;
  1057. float corr_dims[2];
  1058. float theta_scale;
  1059. uint32_t has_ff;
  1060. uint32_t ne02;
  1061. uint32_t s1;
  1062. uint32_t s2;
  1063. int32_t sections[4];
  1064. uint32_t is_imrope;
  1065. uint32_t is_back;
  1066. uint32_t set_rows_stride;
  1067. };
  1068. // For fused rms_norm+mul+rope(+view+set_rows)
  1069. struct vk_op_rms_norm_mul_rope_push_constants {
  1070. vk_op_binary_push_constants bin;
  1071. vk_op_rope_push_constants rope;
  1072. };
  1073. struct vk_op_soft_max_push_constants {
  1074. uint32_t KX;
  1075. uint32_t KY;
  1076. uint32_t ne00;
  1077. uint32_t ne01;
  1078. uint32_t ne02;
  1079. uint32_t ne12;
  1080. uint32_t ne13;
  1081. uint32_t nb11;
  1082. uint32_t nb12;
  1083. uint32_t nb13;
  1084. float scale;
  1085. float max_bias;
  1086. float m0;
  1087. float m1;
  1088. uint32_t n_head_log2;
  1089. uint32_t nrows_x;
  1090. uint32_t has_sinks;
  1091. };
  1092. struct vk_op_argsort_push_constants {
  1093. uint32_t ncols;
  1094. uint32_t ncols_padded;
  1095. uint32_t ncols_padded_log2;
  1096. uint32_t nrows;
  1097. uint32_t order;
  1098. uint32_t outer_start;
  1099. uint32_t outer_end;
  1100. uint32_t inner_start;
  1101. uint32_t inner_end;
  1102. };
  1103. struct vk_op_topk_push_constants {
  1104. uint32_t orig_ncols;
  1105. uint32_t ncols_input;
  1106. uint32_t ncols_output;
  1107. uint32_t k;
  1108. uint32_t nrows;
  1109. uint32_t first_pass;
  1110. uint32_t last_pass;
  1111. };
  1112. struct vk_op_im2col_push_constants {
  1113. uint64_t dst_addr;
  1114. uint32_t batch_offset; uint32_t offset_delta;
  1115. uint32_t IC;
  1116. uint32_t IW; uint32_t IH;
  1117. uint32_t OW; uint32_t OH;
  1118. uint32_t KW; uint32_t KH;
  1119. uint32_t pelements;
  1120. uint32_t CHW;
  1121. int32_t s0; int32_t s1;
  1122. int32_t p0; int32_t p1;
  1123. int32_t d0; int32_t d1;
  1124. uint32_t batch_IC;
  1125. };
  1126. struct vk_op_im2col_3d_push_constants {
  1127. uint64_t dst_addr;
  1128. uint32_t nb10;
  1129. uint32_t nb11;
  1130. uint32_t nb12;
  1131. uint32_t nb13;
  1132. uint32_t s0;
  1133. uint32_t s1;
  1134. uint32_t s2;
  1135. uint32_t p0;
  1136. uint32_t p1;
  1137. uint32_t p2;
  1138. uint32_t d0;
  1139. uint32_t d1;
  1140. uint32_t d2;
  1141. uint32_t IW;
  1142. uint32_t IH;
  1143. uint32_t ID;
  1144. uint32_t IC;
  1145. uint32_t KW;
  1146. uint32_t OH;
  1147. uint32_t KD_KH_KW;
  1148. uint32_t KH_KW;
  1149. uint32_t IC_KD_KH_KW;
  1150. uint32_t N_OD_OH;
  1151. uint32_t OD_OH;
  1152. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1153. uint32_t OH_OW_IC_KD_KH_KW;
  1154. uint32_t OW_IC_KD_KH_KW;
  1155. uint32_t misalign_offsets;
  1156. };
  1157. struct vk_op_timestep_embedding_push_constants {
  1158. uint32_t nb1;
  1159. uint32_t dim;
  1160. uint32_t max_period;
  1161. };
  1162. struct vk_op_conv_transpose_1d_push_constants {
  1163. uint32_t Cout;
  1164. uint32_t Cin;
  1165. uint32_t K;
  1166. uint32_t L;
  1167. uint32_t KL;
  1168. uint32_t nb01;
  1169. uint32_t nb02;
  1170. uint32_t nb11;
  1171. uint32_t nb1;
  1172. int32_t s0;
  1173. };
  1174. struct vk_op_pool2d_push_constants {
  1175. uint32_t IW; uint32_t IH;
  1176. uint32_t OW; uint32_t OH;
  1177. uint32_t OC;
  1178. uint32_t pelements;
  1179. uint32_t op;
  1180. int32_t k0; int32_t k1;
  1181. int32_t s0; int32_t s1;
  1182. int32_t p0; int32_t p1;
  1183. };
  1184. struct vk_op_rwkv_wkv6_push_constants {
  1185. uint32_t B;
  1186. uint32_t T;
  1187. uint32_t C;
  1188. uint32_t H;
  1189. };
  1190. struct vk_op_rwkv_wkv7_push_constants {
  1191. uint32_t B;
  1192. uint32_t T;
  1193. uint32_t C;
  1194. uint32_t H;
  1195. };
  1196. struct vk_op_ssm_scan_push_constants {
  1197. uint32_t nb02, nb03, nb12, nb13;
  1198. uint32_t nb21, nb22, nb31;
  1199. uint32_t nb42, nb43, nb52, nb53;
  1200. uint32_t s_off;
  1201. uint32_t n_head, d_head, n_group, n_tok;
  1202. };
  1203. struct vk_op_ssm_conv_push_constants {
  1204. uint32_t nb01, nb02;
  1205. uint32_t nb11;
  1206. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1207. uint32_t nc, ncs, nr, n_t, n_s;
  1208. };
  1209. struct vk_op_conv2d_push_constants {
  1210. uint32_t Cout;
  1211. uint32_t Cin;
  1212. uint32_t N;
  1213. uint32_t W;
  1214. uint32_t H;
  1215. uint32_t OW;
  1216. uint32_t OH;
  1217. uint32_t nb01;
  1218. uint32_t nb02;
  1219. uint32_t nb03;
  1220. uint32_t nb11;
  1221. uint32_t nb12;
  1222. uint32_t nb13;
  1223. uint32_t nb1;
  1224. uint32_t nb2;
  1225. uint32_t nb3;
  1226. // init_fastdiv_values constants for dividing by OW, OW*OH
  1227. uint32_t OWmp; uint32_t OWL;
  1228. uint32_t OWOHmp; uint32_t OWOHL;
  1229. };
  1230. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1231. // Compute magic values to divide by OW, OW*OH
  1232. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1233. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1234. }
  1235. struct vk_op_conv2d_dw_push_constants {
  1236. uint32_t ne;
  1237. uint32_t batches;
  1238. uint32_t channels;
  1239. uint32_t dst_w;
  1240. uint32_t dst_h;
  1241. uint32_t src_w;
  1242. uint32_t src_h;
  1243. uint32_t knl_w;
  1244. uint32_t knl_h;
  1245. int32_t stride_x;
  1246. int32_t stride_y;
  1247. int32_t pad_x;
  1248. int32_t pad_y;
  1249. int32_t dilation_x;
  1250. int32_t dilation_y;
  1251. };
  1252. struct vk_op_upscale_push_constants {
  1253. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1254. uint32_t ne00; uint32_t ne01;
  1255. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1256. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1257. float sf0; float sf1; float sf2; float sf3;
  1258. float pixel_offset;
  1259. };
  1260. struct vk_op_sum_rows_push_constants
  1261. {
  1262. uint32_t n_cols;
  1263. uint32_t ne01, ne02;
  1264. uint32_t nb01, nb02, nb03;
  1265. uint32_t nb11, nb12, nb13;
  1266. float weight;
  1267. uint32_t misalign_offsets;
  1268. uint32_t ne0_12mp, ne0_12L;
  1269. uint32_t ne0_1mp, ne0_1L;
  1270. };
  1271. 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) {
  1272. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1273. vk_op_sum_rows_push_constants p = {};
  1274. p.n_cols = (uint32_t)n_cols;
  1275. p.ne01 = (uint32_t)src->ne[1];
  1276. p.ne02 = (uint32_t)src->ne[2];
  1277. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1278. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1279. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1280. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1281. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1282. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1283. p.weight = 1.0f;
  1284. return p;
  1285. }
  1286. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1287. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1288. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1289. }
  1290. // Allow pre-recording command buffers
  1291. struct vk_staging_memcpy {
  1292. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1293. void * dst;
  1294. const void * src;
  1295. size_t n;
  1296. };
  1297. struct vk_staging_memset {
  1298. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1299. void * dst;
  1300. uint32_t val;
  1301. size_t n;
  1302. };
  1303. struct vk_context_struct {
  1304. vk_submission * s;
  1305. std::vector<vk_sequence> seqs;
  1306. int exit_tensor_idx;
  1307. std::vector<vk_staging_memcpy> in_memcpys;
  1308. std::vector<vk_staging_memcpy> out_memcpys;
  1309. std::vector<vk_staging_memset> memsets;
  1310. vk_command_pool * p {};
  1311. };
  1312. typedef std::shared_ptr<vk_context_struct> vk_context;
  1313. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1314. struct ggml_vk_garbage_collector {
  1315. std::vector<vk_semaphore> tl_semaphores;
  1316. std::vector<vk_semaphore> semaphores;
  1317. std::vector<vk::Event> events;
  1318. std::vector<vk_context> contexts;
  1319. };
  1320. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1321. static void ggml_vk_load_shaders(vk_device& device);
  1322. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1323. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1324. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1325. static std::string format_size(size_t size) {
  1326. const size_t kib = 1024;
  1327. const size_t mib = kib * 1024;
  1328. const size_t gib = mib * 1024;
  1329. std::ostringstream oss;
  1330. oss << std::fixed << std::setprecision(2);
  1331. if (size >= gib) {
  1332. oss << static_cast<double>(size) / gib << " GiB";
  1333. } else if (size >= mib) {
  1334. oss << static_cast<double>(size) / mib << " MiB";
  1335. } else if (size >= kib) {
  1336. oss << static_cast<double>(size) / kib << " KiB";
  1337. } else {
  1338. oss << size << " B";
  1339. }
  1340. return oss.str();
  1341. }
  1342. class vk_memory_logger {
  1343. public:
  1344. vk_memory_logger(): total_device(0), total_host(0) {}
  1345. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1346. void log_deallocation(vk_buffer_ref buf_ref);
  1347. private:
  1348. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1349. size_t total_device;
  1350. size_t total_host;
  1351. };
  1352. #else
  1353. #define VK_LOG_MEMORY(msg) ((void) 0)
  1354. #endif // GGML_VULKAN_MEMORY_DEBUG
  1355. static bool vk_perf_logger_enabled = false;
  1356. static bool vk_perf_logger_concurrent = false;
  1357. static bool vk_enable_sync_logger = false;
  1358. // number of calls between perf logger prints
  1359. static uint32_t vk_perf_logger_frequency = 1;
  1360. class vk_perf_logger {
  1361. public:
  1362. void print_timings(bool force = false) {
  1363. if (timings.empty()) {
  1364. return;
  1365. }
  1366. print_count++;
  1367. if ((print_count % vk_perf_logger_frequency) != 0 && !force) {
  1368. return;
  1369. }
  1370. print_count = 0;
  1371. uint64_t total_all_op_times = 0;
  1372. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1373. for (const auto & t : timings) {
  1374. uint64_t total_op_times = 0;
  1375. for (const auto & time : t.second) {
  1376. total_op_times += time;
  1377. }
  1378. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1379. << " us = " << (total_op_times / 1000.0) << " us";
  1380. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1381. auto it = flops.find(t.first);
  1382. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1383. uint64_t total_op_flops = 0;
  1384. for (const auto & elem : it->second) {
  1385. total_op_flops += elem;
  1386. }
  1387. std::cerr << " ("
  1388. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1389. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1390. << " GFLOPS/s)";
  1391. }
  1392. total_all_op_times += total_op_times;
  1393. std::cerr << std::endl;
  1394. }
  1395. if (timings.size() > 0) {
  1396. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1397. }
  1398. timings.clear();
  1399. flops.clear();
  1400. }
  1401. std::string get_node_fusion_name(const ggml_tensor * node, const char *fusion_name, uint64_t *n_flops) {
  1402. *n_flops = 0;
  1403. std::string fusion_str;
  1404. if (fusion_name) {
  1405. fusion_str = fusion_name + std::string(" ");
  1406. }
  1407. if (node->op == GGML_OP_UNARY) {
  1408. return fusion_str + ggml_unary_op_name(ggml_get_unary_op(node));
  1409. }
  1410. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1411. const uint64_t m = node->ne[0];
  1412. const uint64_t n = node->ne[1];
  1413. const uint64_t k = node->src[1]->ne[0];
  1414. const uint64_t batch = node->ne[2] * node->ne[3];
  1415. std::string name = ggml_op_name(node->op);
  1416. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1417. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1418. name += "_VEC";
  1419. }
  1420. name += " ";
  1421. name += ggml_type_name(node->src[0]->type);
  1422. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1423. if (node->op == GGML_OP_MUL_MAT_ID) {
  1424. name += " n_expert=" + std::to_string(node->src[0]->ne[2]);
  1425. }
  1426. if (batch > 1) {
  1427. name += " batch=" + std::to_string(batch);
  1428. }
  1429. name = fusion_str + name;
  1430. *n_flops = m * n * (k + (k - 1)) * batch;
  1431. return name;
  1432. }
  1433. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1434. std::string name = ggml_op_name(node->op);
  1435. ggml_tensor * knl = node->src[0];
  1436. uint64_t OW = node->ne[0];
  1437. uint64_t OH = node->ne[1];
  1438. uint64_t N = node->ne[3];
  1439. uint64_t Cout = node->ne[2];
  1440. uint64_t KW = knl->ne[0];
  1441. uint64_t KH = knl->ne[1];
  1442. uint64_t Cin = node->src[1]->ne[2];
  1443. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1444. uint64_t size_M = Cout;
  1445. uint64_t size_K = Cin * KW * KH;
  1446. uint64_t size_N = N * OW * OH;
  1447. *n_flops = size_M * size_N * (size_K + (size_K - 1));
  1448. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1449. ", N=N*OW*OH=" + std::to_string(size_N);
  1450. name = fusion_str + name;
  1451. return name;
  1452. }
  1453. if (node->op == GGML_OP_RMS_NORM) {
  1454. std::string name = ggml_op_name(node->op);
  1455. 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]) + ")";
  1456. name = fusion_str + name;
  1457. return name;
  1458. }
  1459. if (node->op == GGML_OP_FLASH_ATTN_EXT) {
  1460. const ggml_tensor * dst = node;
  1461. const ggml_tensor * q = node->src[0];
  1462. const ggml_tensor * k = node->src[1];
  1463. const ggml_tensor * v = node->src[2];
  1464. const ggml_tensor * m = node->src[3];
  1465. std::stringstream name;
  1466. name << fusion_str;
  1467. name << ggml_op_name(node->op) <<
  1468. " dst(" << dst->ne[0] << "," << dst->ne[1] << "," << dst->ne[2] << "," << dst->ne[3] << "), " <<
  1469. " q(" << q->ne[0] << "," << q->ne[1] << "," << q->ne[2] << "," << q->ne[3] << "), " <<
  1470. " k(" << k->ne[0] << "," << k->ne[1] << "," << k->ne[2] << "," << k->ne[3] << "), " <<
  1471. " v(" << v->ne[0] << "," << v->ne[1] << "," << v->ne[2] << "," << v->ne[3] << "), " <<
  1472. " m(" << (m?m->ne[0]:0) << "," << (m?m->ne[1]:0) << "," << (m?m->ne[2]:0) << "," << (m?m->ne[3]:0) << ")";
  1473. return name.str();
  1474. }
  1475. if (node->op == GGML_OP_TOP_K) {
  1476. std::stringstream name;
  1477. name << fusion_str;
  1478. name << ggml_op_name(node->op) <<
  1479. " K=" << node->ne[0] <<
  1480. " (" << node->src[0]->ne[0] << "," << node->src[0]->ne[1] << "," << node->src[0]->ne[2] << "," << node->src[0]->ne[3] << ")";
  1481. return name.str();
  1482. }
  1483. return fusion_str + ggml_op_name(node->op);
  1484. }
  1485. void log_timing(const ggml_tensor * node, const char *fusion_name, uint64_t time) {
  1486. uint64_t n_flops;
  1487. std::string name = get_node_fusion_name(node, fusion_name, &n_flops);
  1488. if (n_flops) {
  1489. flops[name].push_back(n_flops);
  1490. }
  1491. timings[name].push_back(time);
  1492. }
  1493. void log_timing(const std::vector<ggml_tensor *> &nodes, const std::vector<const char *> &names, uint64_t time) {
  1494. uint64_t total_flops = 0;
  1495. std::string name;
  1496. for (size_t n = 0; n < nodes.size(); ++n) {
  1497. uint64_t n_flops = 0;
  1498. name += get_node_fusion_name(nodes[n], names[n], &n_flops);
  1499. total_flops += n_flops;
  1500. if (n != nodes.size() - 1) {
  1501. name += ", ";
  1502. }
  1503. }
  1504. if (total_flops) {
  1505. flops[name].push_back(total_flops);
  1506. }
  1507. timings[name].push_back(time);
  1508. }
  1509. private:
  1510. std::map<std::string, std::vector<uint64_t>> timings;
  1511. std::map<std::string, std::vector<uint64_t>> flops;
  1512. uint32_t print_count {};
  1513. };
  1514. struct ggml_backend_vk_context {
  1515. std::string name;
  1516. vk_device device;
  1517. size_t semaphore_idx, event_idx;
  1518. ggml_vk_garbage_collector gc;
  1519. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1520. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging;
  1521. vk::Fence fence, almost_ready_fence;
  1522. bool submit_pending {};
  1523. bool almost_ready_fence_pending {};
  1524. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1525. // write partial sums to accumulate the square of the vector components
  1526. bool do_add_rms_partials_offset_calculation;
  1527. bool do_add_rms_partials;
  1528. uint64_t last_total_mul_mat_bytes {};
  1529. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1530. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1531. const ggml_tensor * prealloc_y_last_tensor_used {};
  1532. // Track which nodes have been used since the last sync, and whether they were written to
  1533. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1534. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1535. // Track which prealloc buffers have pending reads that need to be synchronized.
  1536. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1537. // and set to true after the buffer contents are consumed.
  1538. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1539. vk_context_ref compute_ctx;
  1540. vk_context_ref transfer_ctx;
  1541. std::vector<vk_context_ref> tensor_ctxs;
  1542. std::vector<vk::DescriptorPool> descriptor_pools;
  1543. std::vector<vk::DescriptorSet> descriptor_sets;
  1544. uint32_t descriptor_set_idx {};
  1545. uint32_t pipeline_descriptor_set_requirements {};
  1546. vk_command_pool compute_cmd_pool;
  1547. vk_command_pool transfer_cmd_pool;
  1548. // number of additional consecutive nodes that are being fused with the
  1549. // node currently being processed
  1550. int num_additional_fused_ops {};
  1551. // Bitmask of which fused ops need to write an intermediate value to memory.
  1552. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1553. // If there's no fusion, bit 0 is still set.
  1554. int fused_ops_write_mask {};
  1555. topk_moe_mode fused_topk_moe_mode {};
  1556. bool fused_topk_moe_scale {};
  1557. // for GGML_VK_PERF_LOGGER
  1558. std::unique_ptr<vk_perf_logger> perf_logger;
  1559. vk::QueryPool query_pool;
  1560. std::vector<const char *> query_fusion_names;
  1561. std::vector<int> query_fusion_node_count;
  1562. std::vector<ggml_tensor *> query_nodes;
  1563. std::vector<int> query_node_idx;
  1564. int32_t num_queries {};
  1565. int32_t query_idx {};
  1566. };
  1567. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1568. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1569. if (tensor->view_src) {
  1570. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1571. }
  1572. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1573. }
  1574. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  1575. {
  1576. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  1577. }
  1578. 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) {
  1579. GGML_UNUSED(p);
  1580. GGML_UNUSED(src0);
  1581. GGML_UNUSED(src1);
  1582. GGML_UNUSED(src2);
  1583. GGML_UNUSED(src3);
  1584. GGML_UNUSED(dst);
  1585. static_assert(!std::is_const<T>::value, "unexpected type");
  1586. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  1587. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  1588. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  1589. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  1590. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  1591. }
  1592. 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) {
  1593. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1594. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1595. p.b_offset = b_offset;
  1596. p.d_offset = d_offset;
  1597. GGML_UNUSED(src0);
  1598. GGML_UNUSED(src2);
  1599. GGML_UNUSED(src3);
  1600. }
  1601. 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) {
  1602. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1603. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1604. p.b_offset = b_offset;
  1605. p.d_offset = d_offset;
  1606. GGML_UNUSED(src0);
  1607. GGML_UNUSED(src2);
  1608. GGML_UNUSED(src3);
  1609. }
  1610. struct ggml_backend_vk_buffer_context {
  1611. vk_device_ref device;
  1612. vk_buffer dev_buffer;
  1613. std::string name;
  1614. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1615. device(device),
  1616. dev_buffer(dev_buffer),
  1617. name(name) {
  1618. }
  1619. ~ggml_backend_vk_buffer_context() {
  1620. ggml_vk_destroy_buffer(dev_buffer);
  1621. }
  1622. };
  1623. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1624. static std::mutex log_mutex;
  1625. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1626. std::lock_guard<std::mutex> guard(log_mutex);
  1627. vk_buffer buf = buf_ref.lock();
  1628. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1629. const std::string type = device ? "device" : "host";
  1630. allocations[buf->buffer] = size;
  1631. total_device += device ? size : 0;
  1632. total_host += device ? 0 : size;
  1633. 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));
  1634. }
  1635. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1636. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1637. return;
  1638. }
  1639. std::lock_guard<std::mutex> guard(log_mutex);
  1640. vk_buffer buf = buf_ref.lock();
  1641. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1642. std::string type = device ? "device" : "host";
  1643. auto it = allocations.find(buf->buffer);
  1644. total_device -= device ? it->second : 0;
  1645. total_host -= device ? 0 : it->second;
  1646. if (it != allocations.end()) {
  1647. 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));
  1648. allocations.erase(it);
  1649. } else {
  1650. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1651. }
  1652. }
  1653. #endif // GGML_VULKAN_MEMORY_DEBUG
  1654. struct vk_instance_t {
  1655. vk::Instance instance;
  1656. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1657. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1658. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1659. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1660. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1661. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1662. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1663. std::vector<size_t> device_indices;
  1664. std::vector<bool> device_supports_membudget;
  1665. vk_device devices[GGML_VK_MAX_DEVICES];
  1666. };
  1667. static bool vk_instance_initialized = false;
  1668. static vk_instance_t vk_instance;
  1669. #ifdef GGML_VULKAN_CHECK_RESULTS
  1670. static size_t vk_skip_checks;
  1671. static size_t vk_output_tensor;
  1672. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1673. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1674. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1675. #endif
  1676. 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);
  1677. static void ggml_backend_vk_free(ggml_backend_t backend);
  1678. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1679. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1680. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1681. return range;
  1682. }
  1683. // Wait for ctx->fence to be signaled.
  1684. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1685. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1686. // during this wait.
  1687. if (ctx->almost_ready_fence_pending) {
  1688. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1689. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1690. ctx->almost_ready_fence_pending = false;
  1691. }
  1692. // Spin (w/pause) waiting for the graph to finish executing.
  1693. vk::Result result;
  1694. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1695. if (result != vk::Result::eNotReady) {
  1696. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1697. exit(1);
  1698. }
  1699. for (uint32_t i = 0; i < 100; ++i) {
  1700. YIELD();
  1701. YIELD();
  1702. YIELD();
  1703. YIELD();
  1704. YIELD();
  1705. YIELD();
  1706. YIELD();
  1707. YIELD();
  1708. YIELD();
  1709. YIELD();
  1710. }
  1711. }
  1712. ctx->device->device.resetFences({ ctx->fence });
  1713. }
  1714. // variables to track number of compiles in progress
  1715. static uint32_t compile_count = 0;
  1716. static std::mutex compile_count_mutex;
  1717. static std::condition_variable compile_count_cond;
  1718. 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,
  1719. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1720. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1721. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1722. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1723. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1724. GGML_ASSERT(parameter_count > 0);
  1725. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1726. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1727. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1728. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1729. vk::PushConstantRange pcr(
  1730. vk::ShaderStageFlagBits::eCompute,
  1731. 0,
  1732. pipeline->push_constant_size
  1733. );
  1734. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1735. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1736. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1737. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1738. specialization_entries[i].constantID = i;
  1739. specialization_entries[i].offset = i * sizeof(uint32_t);
  1740. specialization_entries[i].size = sizeof(uint32_t);
  1741. }
  1742. vk::SpecializationInfo specialization_info(
  1743. specialization_entries.size(),
  1744. specialization_entries.data(),
  1745. specialization_constants.size() * sizeof(uint32_t),
  1746. specialization_constants.data()
  1747. );
  1748. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1749. if (device->subgroup_require_full_support && require_full_subgroups) {
  1750. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1751. }
  1752. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1753. pipeline_shader_stage_create_flags,
  1754. vk::ShaderStageFlagBits::eCompute,
  1755. pipeline->shader_module,
  1756. entrypoint.c_str(),
  1757. &specialization_info);
  1758. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1759. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1760. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1761. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1762. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1763. }
  1764. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1765. device->pipeline_executable_properties_support ?
  1766. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1767. vk::PipelineCreateFlags{},
  1768. pipeline_shader_create_info,
  1769. pipeline->layout);
  1770. vk::PipelineRobustnessCreateInfoEXT rci;
  1771. if (device->pipeline_robustness && disable_robustness) {
  1772. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1773. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1774. compute_pipeline_create_info.setPNext(&rci);
  1775. }
  1776. try {
  1777. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1778. } catch (const vk::SystemError& e) {
  1779. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1780. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1781. throw e;
  1782. }
  1783. pipeline->compiled = true;
  1784. if (vk_instance.debug_utils_support) {
  1785. vk::DebugUtilsObjectNameInfoEXT duoni;
  1786. duoni.objectType = vk::ObjectType::ePipeline;
  1787. duoni.pObjectName = pipeline->name.c_str();
  1788. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1789. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1790. }
  1791. if (device->pipeline_executable_properties_support) {
  1792. vk::PipelineExecutableInfoKHR executableInfo;
  1793. executableInfo.pipeline = pipeline->pipeline;
  1794. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1795. for (auto & s : statistics) {
  1796. // "Register Count" is reported by NVIDIA drivers.
  1797. if (strcmp(s.name, "Register Count") == 0) {
  1798. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1799. pipeline->register_count = (uint32_t)s.value.u64;
  1800. }
  1801. }
  1802. }
  1803. device->all_pipelines.push_back(pipeline);
  1804. {
  1805. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1806. assert(compile_count > 0);
  1807. compile_count--;
  1808. }
  1809. compile_count_cond.notify_all();
  1810. }
  1811. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1812. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1813. device.destroyPipelineLayout(pipeline->layout);
  1814. device.destroyShaderModule(pipeline->shader_module);
  1815. device.destroyPipeline(pipeline->pipeline);
  1816. }
  1817. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1818. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1819. ctx->pipeline_descriptor_set_requirements += n;
  1820. if (!pipeline->compiled) {
  1821. pipeline->needed = true;
  1822. ggml_vk_load_shaders(ctx->device);
  1823. }
  1824. ggml_pipeline_allocate_descriptor_sets(ctx);
  1825. }
  1826. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1827. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1828. // Enough descriptors are available
  1829. return;
  1830. }
  1831. vk_device& device = ctx->device;
  1832. // Grow by 50% to avoid frequent allocations
  1833. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1834. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1835. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1836. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1837. while (to_alloc > 0) {
  1838. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1839. to_alloc -= alloc_count;
  1840. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1841. if (pool_idx >= ctx->descriptor_pools.size()) {
  1842. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1843. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1844. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1845. }
  1846. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1847. for (uint32_t i = 0; i < alloc_count; i++) {
  1848. layouts[i] = device->dsl;
  1849. }
  1850. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1851. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1852. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1853. pool_idx++;
  1854. }
  1855. }
  1856. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1857. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1858. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1859. // Reuse command buffer
  1860. return p.cmd_buffers[p.cmd_buffer_idx++];
  1861. }
  1862. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1863. p.pool,
  1864. vk::CommandBufferLevel::ePrimary,
  1865. 1);
  1866. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1867. auto buf = cmd_buffers.front();
  1868. p.cmd_buffers.push_back(buf);
  1869. p.cmd_buffer_idx++;
  1870. return buf;
  1871. }
  1872. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1873. if (ctx->seqs.empty()) {
  1874. if (fence) {
  1875. std::lock_guard<std::mutex> guard(queue_mutex);
  1876. ctx->p->q->queue.submit({}, fence);
  1877. }
  1878. return;
  1879. }
  1880. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1881. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1882. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1883. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1884. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1885. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1886. std::vector<vk::SubmitInfo> submit_infos;
  1887. int idx = -1;
  1888. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1889. size_t reserve = 0;
  1890. for (const auto& sequence : ctx->seqs) {
  1891. reserve += sequence.size();
  1892. }
  1893. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1894. tl_wait_semaphores.reserve(reserve);
  1895. tl_wait_vals.reserve(reserve);
  1896. tl_signal_semaphores.reserve(reserve);
  1897. tl_signal_vals.reserve(reserve);
  1898. tl_submit_infos.reserve(reserve);
  1899. submit_infos.reserve(reserve);
  1900. stage_flags.reserve(reserve);
  1901. for (const auto& sequence : ctx->seqs) {
  1902. for (const auto& submission : sequence) {
  1903. stage_flags.push_back({});
  1904. idx++;
  1905. tl_wait_vals.push_back({});
  1906. tl_wait_semaphores.push_back({});
  1907. tl_signal_vals.push_back({});
  1908. tl_signal_semaphores.push_back({});
  1909. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1910. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1911. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1912. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1913. }
  1914. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1915. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1916. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1917. }
  1918. tl_submit_infos.push_back({
  1919. (uint32_t) submission.wait_semaphores.size(),
  1920. tl_wait_vals[idx].data(),
  1921. (uint32_t) submission.signal_semaphores.size(),
  1922. tl_signal_vals[idx].data(),
  1923. });
  1924. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1925. tl_submit_infos[idx].pNext = nullptr;
  1926. vk::SubmitInfo si{
  1927. (uint32_t) submission.wait_semaphores.size(),
  1928. tl_wait_semaphores[idx].data(),
  1929. stage_flags[idx].data(),
  1930. 1,
  1931. &submission.buffer,
  1932. (uint32_t) submission.signal_semaphores.size(),
  1933. tl_signal_semaphores[idx].data(),
  1934. };
  1935. si.setPNext(&tl_submit_infos[idx]);
  1936. submit_infos.push_back(si);
  1937. }
  1938. }
  1939. std::lock_guard<std::mutex> guard(queue_mutex);
  1940. ctx->p->q->queue.submit(submit_infos, fence);
  1941. ctx->seqs.clear();
  1942. }
  1943. 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) {
  1944. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1945. const uint32_t qfsize = queue_family_props.size();
  1946. // Try with avoid preferences first
  1947. for (uint32_t i = 0; i < qfsize; i++) {
  1948. 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)) {
  1949. return i;
  1950. }
  1951. }
  1952. // Fall back to only required
  1953. for (size_t i = 0; i < qfsize; i++) {
  1954. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1955. return i;
  1956. }
  1957. }
  1958. // Fall back to reusing compute queue
  1959. for (size_t i = 0; i < qfsize; i++) {
  1960. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1961. return i;
  1962. }
  1963. }
  1964. // Fall back to ignoring min_num_queries
  1965. for (size_t i = 0; i < qfsize; i++) {
  1966. if (queue_family_props[i].queueFlags & required) {
  1967. return i;
  1968. }
  1969. }
  1970. // 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.
  1971. // 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.
  1972. if (compute_index >= 0) {
  1973. return compute_index;
  1974. }
  1975. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1976. for(auto &q_family : queue_family_props) {
  1977. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1978. }
  1979. abort();
  1980. }
  1981. 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) {
  1982. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1983. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1984. q.queue_family_index = queue_family_index;
  1985. q.transfer_only = transfer_only;
  1986. q.cmd_pool.init(device, &q);
  1987. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1988. q.stage_flags = stage_flags;
  1989. }
  1990. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1991. vk_context result = std::make_shared<vk_context_struct>();
  1992. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1993. ctx->gc.contexts.emplace_back(result);
  1994. result->p = &p;
  1995. return result;
  1996. }
  1997. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1998. vk_context result = std::make_shared<vk_context_struct>();
  1999. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  2000. result->p = &p;
  2001. return result;
  2002. }
  2003. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  2004. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  2005. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  2006. vk::SemaphoreCreateInfo ci{};
  2007. ci.setPNext(&tci);
  2008. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  2009. ctx->gc.semaphores.push_back({ semaphore, 0 });
  2010. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  2011. }
  2012. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  2013. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  2014. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  2015. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  2016. vk::SemaphoreCreateInfo ci{};
  2017. ci.setPNext(&tci);
  2018. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  2019. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  2020. }
  2021. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  2022. }
  2023. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  2024. if (ctx->event_idx >= ctx->gc.events.size()) {
  2025. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  2026. }
  2027. return ctx->gc.events[ctx->event_idx++];
  2028. }
  2029. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  2030. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  2031. // Requires command buffers to be done
  2032. device->device.resetCommandPool(p.pool);
  2033. p.cmd_buffer_idx = 0;
  2034. }
  2035. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  2036. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  2037. // Arbitrary frequency to cleanup/reuse command buffers
  2038. static constexpr uint32_t cleanup_frequency = 10;
  2039. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  2040. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  2041. }
  2042. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  2043. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  2044. }
  2045. }
  2046. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  2047. std::vector<uint32_t> indices;
  2048. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  2049. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  2050. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  2051. (flags & memory_type.propertyFlags) == flags &&
  2052. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  2053. indices.push_back(i);
  2054. }
  2055. }
  2056. return indices;
  2057. }
  2058. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list,
  2059. void *import_ptr = nullptr) {
  2060. 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]) << ")");
  2061. if (size > device->max_buffer_size) {
  2062. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  2063. }
  2064. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  2065. if (size == 0) {
  2066. buf->size = 0;
  2067. return buf;
  2068. }
  2069. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  2070. vk::MemoryAllocateFlags mem_flags {};
  2071. if (device->buffer_device_address) {
  2072. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  2073. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  2074. }
  2075. vk::BufferCreateInfo buffer_create_info{
  2076. vk::BufferCreateFlags(),
  2077. size,
  2078. usage_flags,
  2079. vk::SharingMode::eExclusive,
  2080. 0,
  2081. nullptr,
  2082. };
  2083. vk::ExternalMemoryBufferCreateInfo external_memory_bci;
  2084. if (import_ptr) {
  2085. external_memory_bci.handleTypes = vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT;
  2086. buffer_create_info.setPNext(&external_memory_bci);
  2087. }
  2088. buf->buffer = device->device.createBuffer(buffer_create_info);
  2089. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  2090. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2091. const vk::MemoryPriorityAllocateInfoEXT mem_priority_info { 1.0f };
  2092. vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  2093. if (device->memory_priority) {
  2094. mem_flags_info.setPNext(&mem_priority_info);
  2095. }
  2096. if (import_ptr) {
  2097. vk::MemoryHostPointerPropertiesEXT host_pointer_props;
  2098. try {
  2099. host_pointer_props = device->device.getMemoryHostPointerPropertiesEXT(vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT, import_ptr);
  2100. } catch (vk::SystemError& e) {
  2101. GGML_LOG_WARN("ggml_vulkan: Failed getMemoryHostPointerPropertiesEXT (%s)\n", e.what());
  2102. device->device.destroyBuffer(buf->buffer);
  2103. return {};
  2104. }
  2105. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2106. uint32_t memory_type_idx;
  2107. vk::MemoryPropertyFlags property_flags = *req_flags_list.begin();
  2108. for (memory_type_idx = 0; memory_type_idx < 32; ++memory_type_idx) {
  2109. if (!(host_pointer_props.memoryTypeBits & (1u << memory_type_idx))) {
  2110. continue;
  2111. }
  2112. if (!(mem_req.memoryTypeBits & (1u << memory_type_idx))) {
  2113. continue;
  2114. }
  2115. vk::MemoryType memory_type = mem_props.memoryTypes[memory_type_idx];
  2116. // check for visible+coherent+cached. Other flags (e.g. devicelocal) are allowed
  2117. if ((memory_type.propertyFlags & property_flags) == property_flags) {
  2118. property_flags = memory_type.propertyFlags;
  2119. break;
  2120. }
  2121. }
  2122. if (memory_type_idx == 32) {
  2123. GGML_LOG_WARN("ggml_vulkan: Memory type for host allocation not found\n");
  2124. device->device.destroyBuffer(buf->buffer);
  2125. return {};
  2126. }
  2127. buf->memory_property_flags = mem_props.memoryTypes[memory_type_idx].propertyFlags;
  2128. try {
  2129. vk::ImportMemoryHostPointerInfoEXT import_info;
  2130. import_info.handleType = vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT;
  2131. import_info.pHostPointer = import_ptr;
  2132. import_info.setPNext(&mem_flags_info);
  2133. buf->device_memory = device->device.allocateMemory({ size, memory_type_idx, &import_info });
  2134. } catch (const vk::SystemError& e) {
  2135. }
  2136. } else {
  2137. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  2138. const auto & req_flags = *it;
  2139. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  2140. if (memory_type_indices.empty()) {
  2141. continue;
  2142. }
  2143. buf->memory_property_flags = req_flags;
  2144. bool done = false;
  2145. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  2146. try {
  2147. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  2148. done = true;
  2149. break;
  2150. } catch (const vk::SystemError& e) {
  2151. // loop and retry
  2152. // during last attempt throw the exception
  2153. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  2154. device->device.destroyBuffer(buf->buffer);
  2155. throw e;
  2156. }
  2157. }
  2158. }
  2159. if (done) {
  2160. break;
  2161. }
  2162. }
  2163. }
  2164. if (!buf->device_memory) {
  2165. device->device.destroyBuffer(buf->buffer);
  2166. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  2167. }
  2168. buf->ptr = nullptr;
  2169. if (import_ptr) {
  2170. buf->ptr = import_ptr;
  2171. } else {
  2172. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2173. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  2174. }
  2175. }
  2176. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  2177. buf->device = device;
  2178. buf->size = size;
  2179. if (device->buffer_device_address) {
  2180. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  2181. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  2182. }
  2183. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2184. device->memory_logger->log_allocation(buf, size);
  2185. #endif
  2186. return buf;
  2187. }
  2188. 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)) {
  2189. try {
  2190. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  2191. } catch (const vk::SystemError& e) {
  2192. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  2193. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2194. throw e;
  2195. }
  2196. }
  2197. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  2198. vk_buffer buf;
  2199. try {
  2200. if (device->prefer_host_memory) {
  2201. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2202. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2203. } else if (device->uma) {
  2204. // Fall back to host memory type
  2205. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2206. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2207. } else if (device->disable_host_visible_vidmem) {
  2208. if (device->allow_sysmem_fallback) {
  2209. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2210. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2211. } else {
  2212. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  2213. }
  2214. } else {
  2215. // use rebar if available, otherwise fallback to device only visible memory
  2216. if (device->allow_sysmem_fallback) {
  2217. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2218. vk::MemoryPropertyFlagBits::eDeviceLocal,
  2219. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2220. } else {
  2221. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2222. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2223. }
  2224. }
  2225. } catch (const vk::SystemError& e) {
  2226. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  2227. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2228. throw e;
  2229. }
  2230. return buf;
  2231. }
  2232. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  2233. if (buf == nullptr) {
  2234. return;
  2235. }
  2236. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2237. if (buf->device != nullptr) {
  2238. buf->device->memory_logger->log_deallocation(buf);
  2239. }
  2240. #endif
  2241. buf.reset();
  2242. }
  2243. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  2244. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  2245. }
  2246. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  2247. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  2248. const bool transfer_queue = subctx->p->q->transfer_only;
  2249. if (ctx) {
  2250. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  2251. }
  2252. subctx->s->buffer.pipelineBarrier(
  2253. subctx->p->q->stage_flags,
  2254. subctx->p->q->stage_flags,
  2255. {},
  2256. { {
  2257. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  2258. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  2259. } },
  2260. {},
  2261. {}
  2262. );
  2263. }
  2264. static void ggml_vk_set_event(vk_context& ctx, vk::Event& event) {
  2265. VK_LOG_DEBUG("ggml_vk_set_event()");
  2266. ctx->s->buffer.setEvent(
  2267. event,
  2268. ctx->p->q->stage_flags
  2269. );
  2270. }
  2271. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  2272. VK_LOG_DEBUG("ggml_vk_wait_events()");
  2273. if (events.empty()) {
  2274. return;
  2275. }
  2276. ctx->s->buffer.waitEvents(
  2277. events,
  2278. ctx->p->q->stage_flags,
  2279. ctx->p->q->stage_flags,
  2280. {},
  2281. {},
  2282. {}
  2283. );
  2284. }
  2285. // number of rows/cols for flash attention shader
  2286. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2287. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2288. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsk, uint32_t hsv, bool small_cache) {
  2289. if (hsv >= 192) {
  2290. return 2;
  2291. } else if ((hsv | hsk) & 8 || small_cache) {
  2292. return 4;
  2293. } else {
  2294. return 8;
  2295. }
  2296. }
  2297. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2298. // 128 threads split into four subgroups, each subgroup does 1/4
  2299. // of the Bc dimension.
  2300. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2301. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2302. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2303. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2304. if (path == FA_COOPMAT2) {
  2305. return flash_attention_num_small_rows;
  2306. } else {
  2307. return scalar_flash_attention_num_small_rows;
  2308. }
  2309. }
  2310. 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, bool small_cache) {
  2311. GGML_UNUSED(clamp);
  2312. if (path == FA_SCALAR) {
  2313. if (small_rows) {
  2314. return {scalar_flash_attention_num_small_rows, 64};
  2315. } else {
  2316. if ((hsv | hsk) & 8) {
  2317. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2318. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2319. return {get_fa_scalar_num_large_rows(hsk, hsv, small_cache), 64};
  2320. } else {
  2321. return {get_fa_scalar_num_large_rows(hsk, hsv, small_cache), 32};
  2322. }
  2323. }
  2324. }
  2325. if (path == FA_COOPMAT1) {
  2326. if (small_rows) {
  2327. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2328. } else {
  2329. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2330. }
  2331. }
  2332. // small rows, large cols
  2333. if (small_rows) {
  2334. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2335. }
  2336. // small cols to reduce register count
  2337. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2338. if (hsk >= 512 || hsv >= 512) {
  2339. return {32, 32};
  2340. } else {
  2341. return {64, 32};
  2342. }
  2343. }
  2344. return {64, 64};
  2345. }
  2346. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows, bool small_cache) {
  2347. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows, small_cache)[1];
  2348. }
  2349. 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) {
  2350. uint32_t lut_size = 0;
  2351. switch (src0_type) {
  2352. case GGML_TYPE_IQ1_S:
  2353. case GGML_TYPE_IQ1_M:
  2354. lut_size = 2*2048 + 4*2048;
  2355. break;
  2356. case GGML_TYPE_IQ2_XXS:
  2357. lut_size = 8*256;
  2358. break;
  2359. case GGML_TYPE_IQ2_XS:
  2360. lut_size = 8*512;
  2361. break;
  2362. case GGML_TYPE_IQ2_S:
  2363. lut_size = 8*1024;
  2364. break;
  2365. case GGML_TYPE_IQ3_XXS:
  2366. lut_size = 4*256;
  2367. break;
  2368. case GGML_TYPE_IQ3_S:
  2369. lut_size = 4*512;
  2370. break;
  2371. case GGML_TYPE_IQ4_NL:
  2372. case GGML_TYPE_IQ4_XS:
  2373. case GGML_TYPE_MXFP4:
  2374. lut_size = 4*16;
  2375. break;
  2376. default:
  2377. break;
  2378. }
  2379. // Needs to be kept up to date on shader changes
  2380. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2381. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2382. const uint32_t warps = warptile[0] / warptile[10];
  2383. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2384. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2385. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2386. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2387. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2388. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2389. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2390. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2391. return supported;
  2392. }
  2393. struct GpuPipelineConfig {
  2394. // GPU architecture identifier.
  2395. // Example: vk_device_architecture::AMD_GCN
  2396. vk_device_architecture arch;
  2397. // Mapping of pipeline names to their specific subgroup sizes.
  2398. // Example: {"soft_max_f32", 64}
  2399. std::unordered_map<std::string, uint32_t> pipelines;
  2400. // Default subgroup size for this GPU.
  2401. // Defaults to 0 if not explicitly provided.
  2402. uint32_t default_subgroup_size = 0;
  2403. };
  2404. // Pipeline configuration for RDNA1 GPUs.
  2405. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2406. {"soft_max", 64}, {"im2col", 64},
  2407. {"argmax", 64}, {"mul_mat_vec", 64},
  2408. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2409. };
  2410. // Pipeline configuration for RDNA2 GPUs.
  2411. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2412. {"soft_max", 64}, {"im2col", 64},
  2413. };
  2414. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2415. // Define configurations for different GPUs.
  2416. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2417. {
  2418. vk_device_architecture::AMD_RDNA1,
  2419. {
  2420. rdna1_pipelines,
  2421. },
  2422. RDNA_DEFAULT_SUBGROUP_SIZE
  2423. },
  2424. {
  2425. vk_device_architecture::AMD_RDNA2,
  2426. {
  2427. rdna2_pipelines,
  2428. },
  2429. RDNA_DEFAULT_SUBGROUP_SIZE
  2430. },
  2431. };
  2432. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2433. for (const auto &config : gpu_pipeline_configs) {
  2434. if (config.arch == arch) {
  2435. auto pipIt = config.pipelines.find(pipeline_name);
  2436. if (pipIt != config.pipelines.end()) {
  2437. return pipIt->second;
  2438. }
  2439. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2440. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2441. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2442. for (const auto &entry : sorted_pipelines) {
  2443. if (pipeline_name.find(entry.first) != std::string::npos) {
  2444. return entry.second;
  2445. }
  2446. }
  2447. return config.default_subgroup_size;
  2448. }
  2449. }
  2450. return 0; // If no matching configuration is found
  2451. }
  2452. static void ggml_vk_load_shaders(vk_device& device) {
  2453. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2454. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2455. // some shaders have a minimum subgroup size
  2456. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2457. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2458. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2459. 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;
  2460. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2461. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2462. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2463. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2464. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2465. // mulmat
  2466. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2467. l_warptile_id, m_warptile_id, s_warptile_id,
  2468. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2469. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2470. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2471. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2472. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2473. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2474. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2475. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2476. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2477. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2478. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2479. uint32_t l_align, m_align, s_align;
  2480. if (device->coopmat2) {
  2481. // spec constants and tile sizes for non-quant matmul/matmul_id
  2482. l_warptile = { 256, 128, 256, 64, 1 };
  2483. m_warptile = { 256, 128, 128, 64, 0 };
  2484. s_warptile = { 128, 64, 64, 64, 0 };
  2485. l_wg_denoms = {128, 256, 1 };
  2486. m_wg_denoms = {128, 128, 1 };
  2487. s_wg_denoms = { 64, 64, 1 };
  2488. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2489. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2490. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2491. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2492. l_mmq_wg_denoms = { 128, 256, 1 };
  2493. m_mmq_wg_denoms = { 128, 128, 1 };
  2494. s_mmq_wg_denoms = { 32, 64, 1 };
  2495. // spec constants and tile sizes for quant matmul (Qi_K)
  2496. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2497. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2498. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2499. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2500. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2501. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2502. // spec constants and tile sizes for quant matmul_id
  2503. l_warptile_mmqid = { 256, 128, 128, 32, 1, device->subgroup_size };
  2504. m_warptile_mmqid = { 256, 128, 64, 32, 0, device->subgroup_size };
  2505. s_warptile_mmqid = { 256, 128, 64, 32, 0, device->subgroup_size };
  2506. l_mmqid_wg_denoms = { 128, 128, 1 };
  2507. m_mmqid_wg_denoms = { 128, 64, 1 };
  2508. s_mmqid_wg_denoms = { 128, 64, 1 };
  2509. l_align = 128;
  2510. m_align = 64;
  2511. s_align = 32;
  2512. } else {
  2513. // Matrix cores require different warp group sizes
  2514. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2515. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2516. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2517. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2518. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2519. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2520. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2521. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2522. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2523. const uint32_t s_warptile_wm = device->subgroup_size == 8 ? 8 : 32;
  2524. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2525. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2526. s_warptile = { subgroup_size_32, 32, 32, 16, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2527. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2528. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2529. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2530. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2531. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2532. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2533. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, 2, 1, 1, subgroup_size_8 };
  2534. // K-quants use even more registers, mitigate by setting WMITER to 1
  2535. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2536. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2537. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 1, 2, 1, 1, subgroup_size_8 };
  2538. 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 };
  2539. 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 };
  2540. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2541. 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 };
  2542. 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 };
  2543. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2544. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2545. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2546. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2547. 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 };
  2548. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2549. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2550. // chip specific tuning
  2551. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2552. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2553. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2554. } else if (device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && device->architecture == INTEL_XE2) {
  2555. // Xe2/Xe3 with coopmat enabled - warptile performance tuning
  2556. l_warptile = { 512, 128, 128, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2557. l_warptile_mmq = { 512, 128, 128, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2558. }
  2559. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2560. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2561. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2562. l_align = 128;
  2563. m_align = 64;
  2564. s_align = 32;
  2565. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2566. ggml_type t = (ggml_type)i;
  2567. // Disable medium and large matrix multiplication if not enough shared memory is available
  2568. // Check mmq warptiles as the largest configuration
  2569. // Throw an error if not enough for any matrix multiplication is available
  2570. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2571. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2572. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2573. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2574. device->mul_mat_m[i] = false;
  2575. device->mul_mat_l[i] = false;
  2576. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2577. device->mul_mat_l[i] = false;
  2578. }
  2579. // Disable mul_mat_id if not enough shared memory is available
  2580. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2581. device->mul_mat_id_s[i] = false;
  2582. device->mul_mat_id_m[i] = false;
  2583. device->mul_mat_id_l[i] = false;
  2584. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2585. device->mul_mat_id_m[i] = false;
  2586. device->mul_mat_id_l[i] = false;
  2587. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2588. device->mul_mat_id_l[i] = false;
  2589. }
  2590. }
  2591. }
  2592. if (!device->pipeline_matmul_f32) {
  2593. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2594. }
  2595. if (!device->pipeline_matmul_f32_f16) {
  2596. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2597. }
  2598. if (!device->pipeline_matmul_id_f32) {
  2599. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2600. }
  2601. if (!device->pipeline_matmul_bf16) {
  2602. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2603. }
  2604. if (!device->pipeline_matmul_id_bf16) {
  2605. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2606. }
  2607. std::vector<std::future<void>> compiles;
  2608. 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,
  2609. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2610. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2611. if (!require_full_subgroups && required_subgroup_size == 0) {
  2612. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2613. }
  2614. if (!pipeline) {
  2615. pipeline = std::make_shared<vk_pipeline_struct>();
  2616. }
  2617. if (!pipeline->initialized) {
  2618. pipeline->name = name;
  2619. pipeline->parameter_count = parameter_count;
  2620. pipeline->push_constant_size = push_constant_size;
  2621. pipeline->wg_denoms = wg_denoms;
  2622. pipeline->align = align;
  2623. pipeline->initialized = true;
  2624. }
  2625. if (!pipeline->needed || pipeline->compiled) {
  2626. return;
  2627. }
  2628. // TODO: We're no longer benefitting from the async compiles (shaders are
  2629. // compiled individually, as needed) and this complexity can be removed.
  2630. {
  2631. // wait until fewer than N compiles are in progress
  2632. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2633. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2634. while (compile_count >= N) {
  2635. compile_count_cond.wait(guard);
  2636. }
  2637. compile_count++;
  2638. }
  2639. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2640. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2641. };
  2642. 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,
  2643. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2644. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2645. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2646. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2647. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2648. };
  2649. auto const &fa_wg_denoms = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows, bool small_cache) -> std::array<uint32_t, 3> {
  2650. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows, small_cache)[0], 1, 1};
  2651. };
  2652. auto const &fa_spec_constants = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows, bool small_cache) -> std::vector<uint32_t> {
  2653. // For large number of rows, 128 invocations seems to work best.
  2654. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2655. // can't use 256 for D==80.
  2656. // For scalar, use 128 (arbitrary)
  2657. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2658. const uint32_t D = (hsk|hsv);
  2659. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2660. ? scalar_flash_attention_workgroup_size
  2661. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2662. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows, small_cache);
  2663. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2664. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2665. const uint32_t D_lsb = D ^ (D & (D-1));
  2666. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2667. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2668. };
  2669. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2670. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2671. uint32_t HSK = fa.first.HSK; \
  2672. uint32_t HSV = fa.first.HSV; \
  2673. bool small_rows = fa.first.small_rows; \
  2674. bool small_cache = fa.first.small_cache; \
  2675. FaCodePath path = fa.first.path; \
  2676. bool aligned = fa.first.aligned; \
  2677. bool f32acc = fa.first.f32acc; \
  2678. if (path == FAPATH) { \
  2679. if (aligned) { \
  2680. if (f32acc) { \
  2681. 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,small_cache), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows,small_cache), fa_align(FAPATH,HSK,HSV,TYPE,small_rows,small_cache), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2682. } else { \
  2683. 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,small_cache), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows,small_cache), fa_align(FAPATH,HSK,HSV,TYPE,small_rows,small_cache), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2684. } \
  2685. } else { \
  2686. if (f32acc) { \
  2687. 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,small_cache), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows,small_cache), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2688. } else { \
  2689. 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,small_cache), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows,small_cache), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2690. } \
  2691. } \
  2692. } \
  2693. }
  2694. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2695. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2696. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2697. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2698. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2699. if (device->coopmat1_fa_support) {
  2700. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2701. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2702. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2703. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2704. }
  2705. #endif
  2706. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2707. if (device->coopmat2) {
  2708. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2709. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2710. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2711. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2712. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2713. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2714. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2715. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2716. }
  2717. #endif
  2718. #undef CREATE_FA
  2719. const int mul_mat_id_param_count = 5;
  2720. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2721. if (device->coopmat2) {
  2722. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2723. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2724. 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, true); \
  2725. 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, true); \
  2726. 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, true); \
  2727. 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, true); \
  2728. 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, true); \
  2729. 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, true); \
  2730. // Create 2 variants, {f16,f32} accumulator
  2731. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2732. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2733. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2734. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2735. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2736. if (device->coopmat_bf16_support) {
  2737. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2738. }
  2739. #endif
  2740. 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)
  2741. 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)
  2742. 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)
  2743. 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)
  2744. 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)
  2745. 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)
  2746. 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)
  2747. 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)
  2748. 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)
  2749. 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)
  2750. 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)
  2751. 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)
  2752. 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)
  2753. 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)
  2754. 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)
  2755. 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)
  2756. 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)
  2757. 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)
  2758. 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)
  2759. 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)
  2760. GGML_ASSERT(device->subgroup_ballot);
  2761. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 5)
  2762. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2763. if (device->coopmat_bf16_support) {
  2764. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 5)
  2765. }
  2766. #endif
  2767. 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, 5)
  2768. 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, 5)
  2769. 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, 5)
  2770. 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, 5)
  2771. 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, 5)
  2772. 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, 5)
  2773. 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, 5)
  2774. 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, 5)
  2775. 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, 5)
  2776. 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, 5)
  2777. 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, 5)
  2778. 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, 5)
  2779. 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, 5)
  2780. 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, 5)
  2781. 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, 5)
  2782. 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, 5)
  2783. 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, 5)
  2784. 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, 5)
  2785. 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, 5)
  2786. 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, 5)
  2787. #undef CREATE_MM
  2788. #undef CREATE_MM2
  2789. } else
  2790. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2791. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2792. if (device->coopmat_support) {
  2793. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2794. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2795. if (device->mul_mat ## ID ## _l[TYPE]) \
  2796. 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); \
  2797. if (device->mul_mat ## ID ## _m[TYPE]) \
  2798. 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); \
  2799. if (device->mul_mat ## ID ## _s[TYPE]) \
  2800. 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); \
  2801. if (device->mul_mat ## ID ## _l[TYPE]) \
  2802. 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); \
  2803. if (device->mul_mat ## ID ## _m[TYPE]) \
  2804. 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); \
  2805. if (device->mul_mat ## ID ## _s[TYPE]) \
  2806. 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); \
  2807. // Create 2 variants, {f16,f32} accumulator
  2808. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2809. if (device->coopmat_acc_f16_support) { \
  2810. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2811. } \
  2812. if (device->coopmat_acc_f32_support) { \
  2813. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2814. } \
  2815. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2816. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2817. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2818. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2819. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2820. if (device->coopmat_bf16_support) {
  2821. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2822. }
  2823. #endif
  2824. if (device->coopmat_acc_f16_support) {
  2825. 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, );
  2826. 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, );
  2827. 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, );
  2828. 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, );
  2829. 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, );
  2830. 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, );
  2831. 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, );
  2832. 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, );
  2833. 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, );
  2834. 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, );
  2835. 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, );
  2836. 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, );
  2837. 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, );
  2838. 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, );
  2839. 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, );
  2840. 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, );
  2841. 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, );
  2842. 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, );
  2843. 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, );
  2844. 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, );
  2845. } else {
  2846. 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, );
  2847. 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, );
  2848. 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, );
  2849. 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, );
  2850. 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, );
  2851. 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, );
  2852. 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, );
  2853. 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, );
  2854. 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, );
  2855. 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, );
  2856. 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, );
  2857. 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, );
  2858. 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, );
  2859. 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, );
  2860. 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, );
  2861. 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, );
  2862. 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, );
  2863. 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, );
  2864. 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, );
  2865. 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, );
  2866. }
  2867. GGML_ASSERT(device->subgroup_ballot);
  2868. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id);
  2869. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id);
  2870. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id);
  2871. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2872. if (device->coopmat_bf16_support) {
  2873. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id);
  2874. }
  2875. #endif
  2876. 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, mul_mat_id_param_count, _id);
  2877. 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, mul_mat_id_param_count, _id);
  2878. 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, mul_mat_id_param_count, _id);
  2879. 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, mul_mat_id_param_count, _id);
  2880. 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, mul_mat_id_param_count, _id);
  2881. 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, mul_mat_id_param_count, _id);
  2882. 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, mul_mat_id_param_count, _id);
  2883. 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, mul_mat_id_param_count, _id);
  2884. 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, mul_mat_id_param_count, _id);
  2885. 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, mul_mat_id_param_count, _id);
  2886. 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, mul_mat_id_param_count, _id);
  2887. 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, mul_mat_id_param_count, _id);
  2888. 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, mul_mat_id_param_count, _id);
  2889. 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, mul_mat_id_param_count, _id);
  2890. 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, mul_mat_id_param_count, _id);
  2891. 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, mul_mat_id_param_count, _id);
  2892. 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, mul_mat_id_param_count, _id);
  2893. 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, mul_mat_id_param_count, _id);
  2894. 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, mul_mat_id_param_count, _id);
  2895. 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, mul_mat_id_param_count, _id);
  2896. #undef CREATE_MM2
  2897. #undef CREATE_MM
  2898. } else
  2899. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2900. if (device->fp16) {
  2901. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2902. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2903. if (device->mul_mat ## ID ## _l[TYPE]) \
  2904. 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); \
  2905. if (device->mul_mat ## ID ## _m[TYPE]) \
  2906. 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); \
  2907. if (device->mul_mat ## ID ## _s[TYPE]) \
  2908. 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); \
  2909. if (device->mul_mat ## ID ## _l[TYPE]) \
  2910. 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); \
  2911. if (device->mul_mat ## ID ## _m[TYPE]) \
  2912. 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); \
  2913. if (device->mul_mat ## ID ## _s[TYPE]) \
  2914. 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); \
  2915. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2916. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2917. 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); \
  2918. } \
  2919. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2920. 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); \
  2921. } \
  2922. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2923. 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); \
  2924. } \
  2925. // Create 2 variants, {f16,f32} accumulator
  2926. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2927. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2928. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2929. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2930. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2931. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2932. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2933. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2934. 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);
  2935. 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);
  2936. 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);
  2937. 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);
  2938. 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);
  2939. 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);
  2940. 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);
  2941. 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);
  2942. 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);
  2943. 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);
  2944. 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);
  2945. 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);
  2946. 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);
  2947. 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);
  2948. 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);
  2949. 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);
  2950. 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);
  2951. 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);
  2952. 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);
  2953. 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);
  2954. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2955. if (device->integer_dot_product) {
  2956. 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);
  2957. 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);
  2958. 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);
  2959. 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);
  2960. 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);
  2961. 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);
  2962. 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);
  2963. 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);
  2964. 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);
  2965. 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);
  2966. 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);
  2967. }
  2968. #endif
  2969. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2970. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  2971. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  2972. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  2973. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  2974. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2975. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2976. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2977. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2978. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2979. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2980. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2981. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2982. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2983. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2984. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2985. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2986. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2987. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2988. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2989. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2990. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2991. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2992. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2993. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2994. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2995. if (device->integer_dot_product) {
  2996. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2997. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2998. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  2999. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3000. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3001. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3002. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3003. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3004. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3005. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3006. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3007. }
  3008. #endif
  3009. } else {
  3010. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, 0);
  3011. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, 0);
  3012. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, 0);
  3013. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3014. 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, mul_mat_id_param_count, _id, 0);
  3015. 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, mul_mat_id_param_count, _id, 0);
  3016. 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, mul_mat_id_param_count, _id, 0);
  3017. 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, mul_mat_id_param_count, _id, 0);
  3018. 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, mul_mat_id_param_count, _id, 0);
  3019. 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, mul_mat_id_param_count, _id, 0);
  3020. 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, mul_mat_id_param_count, _id, 0);
  3021. 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, mul_mat_id_param_count, _id, 0);
  3022. 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, mul_mat_id_param_count, _id, 0);
  3023. 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, mul_mat_id_param_count, _id, 0);
  3024. 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, mul_mat_id_param_count, _id, 0);
  3025. 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, mul_mat_id_param_count, _id, 0);
  3026. 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, mul_mat_id_param_count, _id, 0);
  3027. 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, mul_mat_id_param_count, _id, 0);
  3028. 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, mul_mat_id_param_count, _id, 0);
  3029. 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, mul_mat_id_param_count, _id, 0);
  3030. 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, mul_mat_id_param_count, _id, 0);
  3031. 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, mul_mat_id_param_count, _id, 0);
  3032. 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, mul_mat_id_param_count, _id, 0);
  3033. 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, mul_mat_id_param_count, _id, 0);
  3034. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3035. if (device->integer_dot_product) {
  3036. 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, mul_mat_id_param_count, _id, 0);
  3037. 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, mul_mat_id_param_count, _id, 0);
  3038. 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, mul_mat_id_param_count, _id, 0);
  3039. 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, mul_mat_id_param_count, _id, 0);
  3040. 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, mul_mat_id_param_count, _id, 0);
  3041. 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, mul_mat_id_param_count, _id, 0);
  3042. 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, mul_mat_id_param_count, _id, 0);
  3043. 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, mul_mat_id_param_count, _id, 0);
  3044. 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, mul_mat_id_param_count, _id, 0);
  3045. 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, mul_mat_id_param_count, _id, 0);
  3046. 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, mul_mat_id_param_count, _id, 0);
  3047. }
  3048. #endif
  3049. }
  3050. #undef CREATE_MM2
  3051. #undef CREATE_MMQ
  3052. #undef CREATE_MM
  3053. } else {
  3054. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  3055. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  3056. if (device->mul_mat ## ID ## _l[TYPE]) \
  3057. 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); \
  3058. if (device->mul_mat ## ID ## _m[TYPE]) \
  3059. 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); \
  3060. if (device->mul_mat ## ID ## _s[TYPE]) \
  3061. 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); \
  3062. if (device->mul_mat ## ID ## _l[TYPE]) \
  3063. 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); \
  3064. if (device->mul_mat ## ID ## _m[TYPE]) \
  3065. 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); \
  3066. if (device->mul_mat ## ID ## _s[TYPE]) \
  3067. 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); \
  3068. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  3069. if (device->mul_mat ## ID ## _l[TYPE]) \
  3070. 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); \
  3071. if (device->mul_mat ## ID ## _m[TYPE]) \
  3072. 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); \
  3073. if (device->mul_mat ## ID ## _s[TYPE]) \
  3074. 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); \
  3075. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3076. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3077. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3078. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3079. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3080. 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);
  3081. 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);
  3082. 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);
  3083. 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);
  3084. 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);
  3085. 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);
  3086. 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);
  3087. 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);
  3088. 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);
  3089. 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);
  3090. 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);
  3091. 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);
  3092. 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);
  3093. 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);
  3094. 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);
  3095. 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);
  3096. 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);
  3097. 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);
  3098. 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);
  3099. 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);
  3100. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3101. if (device->integer_dot_product) {
  3102. 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, );
  3103. 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, );
  3104. 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, );
  3105. 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, );
  3106. 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, );
  3107. 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, );
  3108. 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, );
  3109. 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, );
  3110. 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, );
  3111. 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, );
  3112. }
  3113. #endif
  3114. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  3115. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3116. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3117. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3118. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3119. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3120. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3121. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3122. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3123. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3124. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3125. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3126. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3127. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3128. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3129. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3130. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3131. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3132. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3133. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3134. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3135. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3136. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3137. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3138. 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, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3139. } else {
  3140. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, 0);
  3141. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, 0);
  3142. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, mul_mat_id_param_count, _id, 0);
  3143. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3144. 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, mul_mat_id_param_count, _id, 0);
  3145. 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, mul_mat_id_param_count, _id, 0);
  3146. 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, mul_mat_id_param_count, _id, 0);
  3147. 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, mul_mat_id_param_count, _id, 0);
  3148. 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, mul_mat_id_param_count, _id, 0);
  3149. 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, mul_mat_id_param_count, _id, 0);
  3150. 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, mul_mat_id_param_count, _id, 0);
  3151. 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, mul_mat_id_param_count, _id, 0);
  3152. 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, mul_mat_id_param_count, _id, 0);
  3153. 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, mul_mat_id_param_count, _id, 0);
  3154. 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, mul_mat_id_param_count, _id, 0);
  3155. 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, mul_mat_id_param_count, _id, 0);
  3156. 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, mul_mat_id_param_count, _id, 0);
  3157. 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, mul_mat_id_param_count, _id, 0);
  3158. 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, mul_mat_id_param_count, _id, 0);
  3159. 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, mul_mat_id_param_count, _id, 0);
  3160. 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, mul_mat_id_param_count, _id, 0);
  3161. 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, mul_mat_id_param_count, _id, 0);
  3162. 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, mul_mat_id_param_count, _id, 0);
  3163. 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, mul_mat_id_param_count, _id, 0);
  3164. }
  3165. }
  3166. // reusing CREATE_MM from the fp32 path
  3167. if ((device->coopmat2 || device->coopmat_support)
  3168. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3169. && !device->coopmat_bf16_support
  3170. #endif
  3171. ) {
  3172. // use scalar tile sizes
  3173. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  3174. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  3175. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  3176. l_wg_denoms = {128, 128, 1 };
  3177. m_wg_denoms = { 64, 64, 1 };
  3178. s_wg_denoms = { 32, 32, 1 };
  3179. if (device->vendor_id == VK_VENDOR_ID_INTEL && device->architecture == INTEL_XE2) {
  3180. // Xe2/Xe3 - bf16 warptile performance tuning
  3181. l_warptile = { 512, 128, 128, 16, subgroup_size_8, 32, 2, 4, 4, 1, subgroup_size_8 };
  3182. }
  3183. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3184. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3185. }
  3186. #undef CREATE_MM
  3187. // mul mat vec
  3188. // the number of rows computed per shader depends on GPU model and quant
  3189. uint32_t rm_stdq = 1;
  3190. uint32_t rm_kq = 2;
  3191. uint32_t rm_stdq_int = 1;
  3192. uint32_t rm_kq_int = 1;
  3193. auto const &rm_iq_int = [](uint32_t i) { return i == 0 ? 8u : 4u; };
  3194. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3195. if (device->architecture == AMD_GCN) {
  3196. rm_stdq = 2;
  3197. rm_kq = 4;
  3198. rm_stdq_int = 4;
  3199. }
  3200. } else if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3201. rm_stdq = 2;
  3202. rm_stdq_int = 2;
  3203. }
  3204. uint32_t rm_iq = 2 * rm_kq;
  3205. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  3206. // Ensure a subgroup size >= 16 is available
  3207. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  3208. 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;
  3209. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  3210. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  3211. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  3212. static constexpr uint32_t mul_mat_vec_num_bindings = 5;
  3213. static constexpr uint32_t mul_mat_vec_id_num_bindings = 6;
  3214. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  3215. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  3216. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  3217. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3218. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3219. SHADER_REDUCTION_MODE_SHMEM;
  3220. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3221. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3222. SHADER_REDUCTION_MODE_SHMEM;
  3223. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  3224. 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);
  3225. 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);
  3226. 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);
  3227. 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);
  3228. 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);
  3229. 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);
  3230. 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);
  3231. 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);
  3232. 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);
  3233. 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);
  3234. 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);
  3235. 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);
  3236. 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);
  3237. 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);
  3238. 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);
  3239. 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);
  3240. 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);
  3241. 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);
  3242. 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);
  3243. 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);
  3244. 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);
  3245. 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);
  3246. 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);
  3247. 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);
  3248. 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);
  3249. 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);
  3250. 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);
  3251. 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);
  3252. 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);
  3253. 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);
  3254. 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);
  3255. 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);
  3256. 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);
  3257. 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);
  3258. 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);
  3259. 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);
  3260. 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);
  3261. 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);
  3262. 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);
  3263. 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);
  3264. 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);
  3265. 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);
  3266. 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);
  3267. 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);
  3268. 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);
  3269. 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);
  3270. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3271. if (device->integer_dot_product) {
  3272. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3273. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3274. 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);
  3275. 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);
  3276. 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);
  3277. 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);
  3278. 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);
  3279. 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);
  3280. 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);
  3281. 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);
  3282. 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);
  3283. 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);
  3284. 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);
  3285. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int);
  3286. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int);
  3287. }
  3288. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3289. }
  3290. 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);
  3291. 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);
  3292. 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);
  3293. 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);
  3294. 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);
  3295. 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);
  3296. 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);
  3297. 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);
  3298. 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);
  3299. 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);
  3300. 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);
  3301. 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);
  3302. 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);
  3303. 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);
  3304. 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);
  3305. 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);
  3306. 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);
  3307. 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);
  3308. 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);
  3309. 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);
  3310. 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);
  3311. 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);
  3312. 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);
  3313. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3314. if (device->integer_dot_product) {
  3315. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3316. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3317. 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);
  3318. 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);
  3319. 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);
  3320. 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);
  3321. 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);
  3322. 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);
  3323. 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);
  3324. 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);
  3325. 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);
  3326. 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);
  3327. 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);
  3328. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_q8_1_f32", arr_dmmv_id_iq1_s_q8_1_f32_len[reduc], arr_dmmv_id_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(0), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(0)}, 1, true, use_subgroups, subgroup_size_int);
  3329. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_q8_1_f32", arr_dmmv_id_iq1_m_q8_1_f32_len[reduc], arr_dmmv_id_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(0), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(0)}, 1, true, use_subgroups, subgroup_size_int);
  3330. }
  3331. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3332. }
  3333. #if !defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3334. GGML_UNUSED(rm_stdq_int);
  3335. GGML_UNUSED(rm_kq_int);
  3336. GGML_UNUSED(rm_iq_int);
  3337. #endif
  3338. // dequant shaders
  3339. 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);
  3340. 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);
  3341. 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);
  3342. 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);
  3343. 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);
  3344. 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);
  3345. 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);
  3346. 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);
  3347. 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);
  3348. 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);
  3349. 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);
  3350. 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);
  3351. 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);
  3352. 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);
  3353. 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);
  3354. 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);
  3355. 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);
  3356. 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);
  3357. 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);
  3358. 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);
  3359. 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);
  3360. // get_rows
  3361. 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);
  3362. 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);
  3363. 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);
  3364. 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);
  3365. 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);
  3366. 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);
  3367. 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);
  3368. 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);
  3369. 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);
  3370. 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);
  3371. 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);
  3372. 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);
  3373. 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);
  3374. 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);
  3375. 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);
  3376. 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);
  3377. 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);
  3378. 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);
  3379. 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);
  3380. 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);
  3381. 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);
  3382. 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);
  3383. 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);
  3384. 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);
  3385. 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);
  3386. 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);
  3387. 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);
  3388. 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);
  3389. 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);
  3390. 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);
  3391. 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);
  3392. 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);
  3393. 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);
  3394. 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);
  3395. 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);
  3396. 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);
  3397. 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);
  3398. 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);
  3399. 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);
  3400. 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);
  3401. 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);
  3402. 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);
  3403. 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);
  3404. 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);
  3405. 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);
  3406. 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);
  3407. 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);
  3408. 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);
  3409. 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);
  3410. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3411. 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);
  3412. } else {
  3413. 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);
  3414. }
  3415. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3416. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3417. 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);
  3418. } else {
  3419. 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);
  3420. }
  3421. }
  3422. 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);
  3423. 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);
  3424. 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);
  3425. 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);
  3426. 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);
  3427. 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);
  3428. 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);
  3429. if (device->float_controls_rte_fp16 &&
  3430. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3431. 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);
  3432. 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);
  3433. }
  3434. 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);
  3435. 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);
  3436. 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);
  3437. 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);
  3438. 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);
  3439. 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);
  3440. 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);
  3441. 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);
  3442. 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);
  3443. 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);
  3444. 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);
  3445. 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);
  3446. 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);
  3447. 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);
  3448. 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);
  3449. 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);
  3450. 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);
  3451. 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);
  3452. if (device->float_controls_rte_fp16) {
  3453. 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);
  3454. 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);
  3455. 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);
  3456. 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);
  3457. 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);
  3458. 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);
  3459. } else {
  3460. 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);
  3461. 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);
  3462. 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);
  3463. 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);
  3464. 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);
  3465. 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);
  3466. }
  3467. #define SET_ROWS(itype, rte) \
  3468. 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); \
  3469. 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); \
  3470. 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); \
  3471. 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); \
  3472. 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); \
  3473. 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); \
  3474. 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); \
  3475. 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); \
  3476. 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);
  3477. if (device->float_controls_rte_fp16) {
  3478. SET_ROWS(_i32, _rte)
  3479. SET_ROWS(_i64, _rte)
  3480. } else {
  3481. SET_ROWS(_i32, )
  3482. SET_ROWS(_i64, )
  3483. }
  3484. #undef SET_ROWS
  3485. 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);
  3486. 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);
  3487. 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);
  3488. 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);
  3489. 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);
  3490. 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);
  3491. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3492. std::string s;
  3493. s += std::string(src0_f16 ? "_f16" : "_f32");
  3494. s += std::string(src1_f16 ? "_f16" : "_f32");
  3495. s += std::string(dst_f16 ? "_f16" : "_f32");
  3496. return s;
  3497. };
  3498. bool rte = device->float_controls_rte_fp16;
  3499. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3500. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3501. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3502. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3503. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3504. CREATE_BINARY(add, , {0}, 4)
  3505. CREATE_BINARY(add, _norepeat, {1}, 4)
  3506. CREATE_BINARY(sub, , {0}, 3)
  3507. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3508. CREATE_BINARY(mul, , {0}, 3)
  3509. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3510. CREATE_BINARY(div, , {0}, 3)
  3511. CREATE_BINARY(div, _norepeat, {1}, 3)
  3512. CREATE_BINARY(add_rms, , {0}, 4)
  3513. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3514. #undef CREATE_BINARY
  3515. if (device->multi_add) {
  3516. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3517. 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);
  3518. 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);
  3519. }
  3520. }
  3521. 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);
  3522. 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);
  3523. 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);
  3524. 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);
  3525. 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);
  3526. 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);
  3527. 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);
  3528. 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);
  3529. ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_antialias_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS}, 1);
  3530. 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);
  3531. 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);
  3532. 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);
  3533. 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);
  3534. 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);
  3535. if (device->float_controls_rte_fp16) {
  3536. 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);
  3537. 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);
  3538. } else {
  3539. 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);
  3540. 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);
  3541. }
  3542. 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);
  3543. 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);
  3544. 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);
  3545. 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);
  3546. 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);
  3547. 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);
  3548. 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);
  3549. 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);
  3550. 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);
  3551. #define CREATE_UNARY(name) \
  3552. 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); \
  3553. 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);
  3554. CREATE_UNARY(gelu)
  3555. CREATE_UNARY(gelu_erf)
  3556. CREATE_UNARY(gelu_quick)
  3557. CREATE_UNARY(silu)
  3558. CREATE_UNARY(relu)
  3559. CREATE_UNARY(xielu)
  3560. CREATE_UNARY(neg)
  3561. CREATE_UNARY(tanh)
  3562. CREATE_UNARY(sigmoid)
  3563. CREATE_UNARY(hardsigmoid)
  3564. CREATE_UNARY(hardswish)
  3565. CREATE_UNARY(abs)
  3566. CREATE_UNARY(softplus)
  3567. CREATE_UNARY(step)
  3568. CREATE_UNARY(round)
  3569. CREATE_UNARY(ceil)
  3570. CREATE_UNARY(floor)
  3571. CREATE_UNARY(trunc)
  3572. #undef CREATE_UNARY
  3573. #define CREATE_UNARY_RTE(name) \
  3574. if (device->float_controls_rte_fp16) { \
  3575. 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); \
  3576. 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); \
  3577. } else { \
  3578. 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); \
  3579. 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); \
  3580. }
  3581. CREATE_UNARY_RTE(exp)
  3582. #undef CREATE_UNARY_RTE
  3583. 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);
  3584. 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);
  3585. 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);
  3586. 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);
  3587. 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);
  3588. #define CREATE_GLU(name) \
  3589. if (device->float_controls_rte_fp16) { \
  3590. 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); \
  3591. 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); \
  3592. } else { \
  3593. 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); \
  3594. 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); \
  3595. }
  3596. CREATE_GLU(geglu)
  3597. CREATE_GLU(reglu)
  3598. CREATE_GLU(swiglu)
  3599. CREATE_GLU(swiglu_oai)
  3600. CREATE_GLU(geglu_erf)
  3601. CREATE_GLU(geglu_quick)
  3602. #undef CREATE_GLU
  3603. 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);
  3604. 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);
  3605. 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);
  3606. 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);
  3607. 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);
  3608. 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);
  3609. 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);
  3610. 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);
  3611. 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);
  3612. 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);
  3613. 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);
  3614. 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);
  3615. 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);
  3616. 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);
  3617. 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);
  3618. 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);
  3619. 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);
  3620. 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);
  3621. if (device->float_controls_rte_fp16) {
  3622. 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);
  3623. 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);
  3624. 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);
  3625. 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);
  3626. 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);
  3627. 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);
  3628. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32_f16, "rope_multi_f32_f16", rope_multi_f32_f16_rte_len, rope_multi_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3629. } else {
  3630. 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);
  3631. 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);
  3632. 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);
  3633. 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);
  3634. 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);
  3635. 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);
  3636. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32_f16, "rope_multi_f32_f16", rope_multi_f32_f16_len, rope_multi_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3637. }
  3638. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3639. uint32_t BLOCK_SIZE = 1u << std::min(i, device->max_workgroup_size_log2);
  3640. if (i <= device->max_workgroup_size_log2 &&
  3641. 2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3642. const uint32_t NCOLS_PADDED_LOG2 = i;
  3643. 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);
  3644. }
  3645. const uint32_t WG_UNROLL_FACTOR = BLOCK_SIZE > 1 ? 2 : 1;
  3646. BLOCK_SIZE /= WG_UNROLL_FACTOR;
  3647. 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);
  3648. }
  3649. for (uint32_t i = 0; i < num_topk_pipelines; ++i) {
  3650. const uint32_t BLOCK_SIZE = 1u << i;
  3651. const uint32_t NCOLS_PADDED_LOG2 = i;
  3652. if (i <= device->max_workgroup_size_log2) {
  3653. uint32_t nary_shmem = 2 * sizeof(int) * BLOCK_SIZE +
  3654. sizeof(int) * device->subgroup_size +
  3655. 2 * sizeof(int) +
  3656. 2 * (BLOCK_SIZE / device->subgroup_size) * sizeof(int);
  3657. if (device->subgroup_arithmetic && device->subgroup_require_full_support && device->subgroup_shuffle && device->subgroup_ballot &&
  3658. nary_shmem <= device->properties.limits.maxComputeSharedMemorySize) {
  3659. 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);
  3660. } else if (2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3661. 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);
  3662. }
  3663. }
  3664. }
  3665. 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);
  3666. 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);
  3667. const uint32_t cumsum_elem_per_thread = (device->vendor_id == VK_VENDOR_ID_AMD || device->vendor_id == VK_VENDOR_ID_INTEL) ? 2 : 4;
  3668. 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}, { 256, device->subgroup_size, cumsum_elem_per_thread }, 1, true, true, device->subgroup_size);
  3669. ggml_vk_create_pipeline(device, device->pipeline_cumsum_small_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 }, 1, true, true, device->subgroup_size);
  3670. ggml_vk_create_pipeline(device, device->pipeline_cumsum_multipass1_f32, "cumsum_multipass1_f32", cumsum_multipass1_f32_len, cumsum_multipass1_f32_data, "main", 3, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3671. ggml_vk_create_pipeline(device, device->pipeline_cumsum_multipass2_f32, "cumsum_multipass2_f32", cumsum_multipass2_f32_len, cumsum_multipass2_f32_data, "main", 3, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3672. 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);
  3673. ggml_vk_create_pipeline(device, device->pipeline_count_experts, "count_experts", count_experts_len, count_experts_data, "main", 2, sizeof(vk_op_count_experts_push_constants), {1, 1, 1}, {}, 1, true);
  3674. for (auto &s : device->pipeline_solve_tri_f32) {
  3675. const vk_solve_tri_pipeline_state &state = s.first;
  3676. // Max number of rows to load at a time, limited by shared memory
  3677. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((state.N + state.K) * sizeof(float));
  3678. // Need at least K invocations, and prefer a minimum of 128 to spread out loading shared memory
  3679. const uint32_t block_size = std::max(128u, 1u << (uint32_t)ceilf(log2f(float(state.K))));
  3680. ggml_vk_create_pipeline(
  3681. device, s.second, "solve_tri_f32",
  3682. solve_tri_f32_len, solve_tri_f32_data, "main", 3,
  3683. sizeof(vk_op_binary_push_constants), {1, 1, 1}, { 0, state.N, state.K, batch_N, block_size }, 1, true);
  3684. }
  3685. #define IM2COL(bda) \
  3686. 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); \
  3687. 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); \
  3688. if (device->float_controls_rte_fp16) { \
  3689. 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); \
  3690. 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); \
  3691. } else { \
  3692. 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); \
  3693. 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); \
  3694. }
  3695. if (device->shader_int64 && device->buffer_device_address) {
  3696. IM2COL(_bda)
  3697. } else {
  3698. IM2COL()
  3699. }
  3700. 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);
  3701. 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);
  3702. 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);
  3703. 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);
  3704. 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);
  3705. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3706. 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);
  3707. 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);
  3708. } else {
  3709. 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);
  3710. 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);
  3711. }
  3712. 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);
  3713. 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);
  3714. 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);
  3715. // conv2d, conv_transpose_2d
  3716. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3717. uint32_t conv2d_WG_SIZE = 256;
  3718. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3719. uint32_t conv2d_TS_K = (s == CONV_SHAPE_64x32) ? 4 : 8;
  3720. uint32_t conv2d_SHMEM_PAD = 4;
  3721. vk_conv_block_size conv2d_BS = vk_conv_block_sizes[s];
  3722. bool conv2d_UNROLL = true;
  3723. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3724. if (device->coopmat2) {
  3725. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3726. }
  3727. #endif
  3728. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3729. conv2d_SHMEM_PAD = 0;
  3730. conv2d_UNROLL = false;
  3731. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3732. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3733. if (s == CONV_SHAPE_128x128 && device->architecture != vk_device_architecture::AMD_GCN) {
  3734. conv2d_UNROLL = false;
  3735. }
  3736. }
  3737. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3738. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3739. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3740. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3741. device->architecture == vk_device_architecture::AMD_GCN;
  3742. if (device->subgroup_shuffle &&
  3743. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3744. allow_collectives_nv &&
  3745. allow_collectives_amd) {
  3746. use_collectives = 1;
  3747. conv2d_BS.CRS = std::min(
  3748. device->subgroup_size,
  3749. conv2d_BS.CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3750. }
  3751. uint32_t conv2d_shmem_req =
  3752. (conv2d_BS.K * (conv2d_BS.CRS + conv2d_SHMEM_PAD) + conv2d_BS.CRS * (conv2d_BS.NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3753. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3754. conv2d_BS.CRS = 8;
  3755. if (use_collectives) {
  3756. conv2d_BS.CRS = std::min(device->subgroup_size, conv2d_BS.CRS);
  3757. }
  3758. }
  3759. std::array<uint32_t, 3> wg_denoms = { conv2d_BS.K, 1, 1 };
  3760. 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 };
  3761. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3762. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3763. const vk_conv2d_pipeline_state &state = c.first; \
  3764. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3765. spec_constants_cpy.push_back(state.s0); \
  3766. spec_constants_cpy.push_back(state.s1); \
  3767. spec_constants_cpy.push_back(state.p0); \
  3768. spec_constants_cpy.push_back(state.p1); \
  3769. spec_constants_cpy.push_back(state.d0); \
  3770. spec_constants_cpy.push_back(state.d1); \
  3771. spec_constants_cpy.push_back(state.KW); \
  3772. spec_constants_cpy.push_back(state.KH); \
  3773. ggml_vk_create_pipeline( \
  3774. device, c.second, #name #type_suffix, \
  3775. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3776. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3777. }
  3778. #define CREATE_CONVS(spv_suffix) \
  3779. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3780. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3781. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3782. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix)
  3783. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3784. if (device->coopmat2) {
  3785. CREATE_CONVS(_cm2)
  3786. } else
  3787. #endif
  3788. if (conv2d_UNROLL) {
  3789. CREATE_CONVS(_unroll)
  3790. } else {
  3791. CREATE_CONVS( )
  3792. }
  3793. #undef CREATE_CONV
  3794. #undef CREATE_CONVS
  3795. }
  3796. 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);
  3797. 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);
  3798. 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);
  3799. 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);
  3800. for (uint32_t use_push = 0; use_push < 2; ++use_push) {
  3801. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3802. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][use_push], "topk_moe_f32_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 4, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, use_push}, 1, true, true, device->subgroup_size);
  3803. }
  3804. }
  3805. for (auto &c : compiles) {
  3806. c.wait();
  3807. }
  3808. }
  3809. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3810. static vk_device ggml_vk_get_device(size_t idx) {
  3811. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3812. if (vk_instance.devices[idx] == nullptr) {
  3813. VK_LOG_DEBUG("Initializing new vk_device");
  3814. vk_device device = std::make_shared<vk_device_struct>();
  3815. vk_instance.devices[idx] = device;
  3816. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3817. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3818. #endif
  3819. size_t dev_num = vk_instance.device_indices[idx];
  3820. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3821. if (dev_num >= physical_devices.size()) {
  3822. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3823. throw std::runtime_error("Device not found");
  3824. }
  3825. device->physical_device = physical_devices[dev_num];
  3826. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3827. device->architecture = get_device_architecture(device->physical_device);
  3828. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3829. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3830. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3831. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3832. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3833. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3834. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3835. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3836. bool fp16_storage = false;
  3837. bool fp16_compute = false;
  3838. bool maintenance4_support = false;
  3839. bool sm_builtins = false;
  3840. bool amd_shader_core_properties2 = false;
  3841. bool pipeline_robustness = false;
  3842. bool coopmat2_support = false;
  3843. bool pipeline_executable_properties_support = false;
  3844. device->coopmat_support = false;
  3845. device->integer_dot_product = false;
  3846. bool bfloat16_support = false;
  3847. for (const auto& properties : ext_props) {
  3848. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3849. maintenance4_support = true;
  3850. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3851. fp16_storage = true;
  3852. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3853. fp16_compute = true;
  3854. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3855. sm_builtins = true;
  3856. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3857. amd_shader_core_properties2 = true;
  3858. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3859. pipeline_robustness = true;
  3860. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3861. device->subgroup_size_control = true;
  3862. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3863. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3864. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3865. device->coopmat_support = true;
  3866. device->coopmat_m = 0;
  3867. device->coopmat_n = 0;
  3868. device->coopmat_k = 0;
  3869. #endif
  3870. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3871. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3872. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3873. coopmat2_support = true;
  3874. #endif
  3875. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3876. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3877. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3878. device->integer_dot_product = true;
  3879. #endif
  3880. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3881. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3882. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3883. bfloat16_support = true;
  3884. #endif
  3885. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3886. pipeline_executable_properties_support = true;
  3887. } else if (strcmp("VK_EXT_memory_priority", properties.extensionName) == 0 &&
  3888. getenv("GGML_VK_ENABLE_MEMORY_PRIORITY")) {
  3889. device->memory_priority = true;
  3890. } else if (strcmp("VK_EXT_external_memory_host", properties.extensionName) == 0) {
  3891. device->external_memory_host = true;
  3892. }
  3893. }
  3894. vk::PhysicalDeviceProperties2 props2;
  3895. vk::PhysicalDeviceMaintenance3Properties props3;
  3896. vk::PhysicalDeviceMaintenance4Properties props4;
  3897. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3898. vk::PhysicalDeviceDriverProperties driver_props;
  3899. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3900. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3901. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3902. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3903. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3904. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3905. vk::PhysicalDeviceExternalMemoryHostPropertiesEXT external_memory_host_props;
  3906. props2.pNext = &props3;
  3907. props3.pNext = &subgroup_props;
  3908. subgroup_props.pNext = &driver_props;
  3909. driver_props.pNext = &vk11_props;
  3910. vk11_props.pNext = &vk12_props;
  3911. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3912. if (maintenance4_support) {
  3913. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3914. last_struct = (VkBaseOutStructure *)&props4;
  3915. }
  3916. if (sm_builtins) {
  3917. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3918. last_struct = (VkBaseOutStructure *)&sm_props;
  3919. }
  3920. if (amd_shader_core_properties2) {
  3921. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3922. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3923. }
  3924. if (device->subgroup_size_control) {
  3925. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3926. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3927. }
  3928. #if defined(VK_NV_cooperative_matrix2)
  3929. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3930. if (coopmat2_support) {
  3931. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3932. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3933. }
  3934. #endif
  3935. if (device->integer_dot_product) {
  3936. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3937. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3938. }
  3939. if (device->external_memory_host) {
  3940. last_struct->pNext = (VkBaseOutStructure *)&external_memory_host_props;
  3941. last_struct = (VkBaseOutStructure *)&external_memory_host_props;
  3942. }
  3943. device->physical_device.getProperties2(&props2);
  3944. device->properties = props2.properties;
  3945. device->vendor_id = device->properties.vendorID;
  3946. device->driver_id = driver_props.driverID;
  3947. if (device->driver_id == vk::DriverId::eMoltenvk) {
  3948. // Disable external_memory_host until https://github.com/KhronosGroup/MoltenVK/pull/2622
  3949. // is available in the Vulkan SDK.
  3950. device->external_memory_host = false;
  3951. }
  3952. // Implementing the async backend interfaces seems broken on older Intel HW,
  3953. // see https://github.com/ggml-org/llama.cpp/issues/17302.
  3954. device->support_async = (device->vendor_id != VK_VENDOR_ID_INTEL ||
  3955. std::string(device->properties.deviceName.data()).find("(DG1)") == std::string::npos) &&
  3956. getenv("GGML_VK_DISABLE_ASYNC") == nullptr;
  3957. if (!device->support_async) {
  3958. GGML_LOG_DEBUG("ggml_vulkan: WARNING: Async execution disabled on certain Intel devices.\n");
  3959. }
  3960. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3961. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3962. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3963. } else if (maintenance4_support) {
  3964. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3965. } else {
  3966. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3967. }
  3968. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3969. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3970. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3971. } else if (maintenance4_support) {
  3972. device->max_buffer_size = props4.maxBufferSize;
  3973. } else {
  3974. device->max_buffer_size = device->max_memory_allocation_size;
  3975. }
  3976. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3977. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3978. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3979. } else {
  3980. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3981. device->suballocation_block_size = 1024*1024*1024;
  3982. }
  3983. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3984. device->subgroup_size = subgroup_props.subgroupSize;
  3985. device->subgroup_size_log2 = uint32_t(log2f(float(device->subgroup_size)));
  3986. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3987. if (sm_builtins) {
  3988. device->shader_core_count = sm_props.shaderSMCount;
  3989. } else if (amd_shader_core_properties2) {
  3990. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3991. } else {
  3992. device->shader_core_count = 0;
  3993. }
  3994. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3995. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3996. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3997. #ifdef __APPLE__
  3998. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3999. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  4000. device->subgroup_arithmetic = false;
  4001. }
  4002. #endif
  4003. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4004. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  4005. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4006. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  4007. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4008. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  4009. device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4010. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote);
  4011. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  4012. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4013. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  4014. device->coopmat_support = false;
  4015. }
  4016. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  4017. device->min_imported_host_pointer_alignment = external_memory_host_props.minImportedHostPointerAlignment;
  4018. device->max_workgroup_size_log2 = uint32_t(log2f(float(device->properties.limits.maxComputeWorkGroupInvocations)));
  4019. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  4020. // Try to find a non-graphics compute queue and transfer-focused queues
  4021. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  4022. 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);
  4023. const float priorities[] = { 1.0f, 1.0f };
  4024. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  4025. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  4026. if (compute_queue_family_index != transfer_queue_family_index) {
  4027. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  4028. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  4029. } else if(!device->single_queue) {
  4030. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  4031. } else {
  4032. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  4033. }
  4034. vk::DeviceCreateInfo device_create_info;
  4035. std::vector<const char *> device_extensions;
  4036. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  4037. VkPhysicalDeviceFeatures2 device_features2;
  4038. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4039. device_features2.pNext = nullptr;
  4040. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  4041. VkPhysicalDeviceVulkan11Features vk11_features;
  4042. vk11_features.pNext = nullptr;
  4043. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4044. device_features2.pNext = &vk11_features;
  4045. VkPhysicalDeviceVulkan12Features vk12_features;
  4046. vk12_features.pNext = nullptr;
  4047. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4048. vk11_features.pNext = &vk12_features;
  4049. last_struct = (VkBaseOutStructure *)&vk12_features;
  4050. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  4051. pl_robustness_features.pNext = nullptr;
  4052. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  4053. pl_robustness_features.pipelineRobustness = VK_FALSE;
  4054. if (pipeline_robustness) {
  4055. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  4056. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  4057. device_extensions.push_back("VK_EXT_pipeline_robustness");
  4058. }
  4059. VkPhysicalDeviceMemoryPriorityFeaturesEXT memory_priority_features;
  4060. memory_priority_features.pNext = nullptr;
  4061. memory_priority_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT;
  4062. memory_priority_features.memoryPriority = VK_FALSE;
  4063. if (device->memory_priority) {
  4064. last_struct->pNext = (VkBaseOutStructure *)&memory_priority_features;
  4065. last_struct = (VkBaseOutStructure *)&memory_priority_features;
  4066. device_extensions.push_back("VK_EXT_memory_priority");
  4067. }
  4068. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  4069. subgroup_size_control_features.pNext = nullptr;
  4070. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  4071. subgroup_size_control_features.computeFullSubgroups = false;
  4072. subgroup_size_control_features.subgroupSizeControl = false;
  4073. if (device->subgroup_size_control) {
  4074. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  4075. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  4076. }
  4077. #if defined(VK_KHR_cooperative_matrix)
  4078. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4079. coopmat_features.pNext = nullptr;
  4080. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4081. coopmat_features.cooperativeMatrix = VK_FALSE;
  4082. if (device->coopmat_support) {
  4083. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4084. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4085. }
  4086. #endif
  4087. #if defined(VK_NV_cooperative_matrix2)
  4088. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  4089. coopmat2_features.pNext = nullptr;
  4090. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  4091. if (coopmat2_support) {
  4092. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  4093. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  4094. device_extensions.push_back("VK_NV_cooperative_matrix2");
  4095. }
  4096. #endif
  4097. #if defined(VK_KHR_shader_bfloat16)
  4098. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4099. bfloat16_features.pNext = nullptr;
  4100. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4101. if (bfloat16_support) {
  4102. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4103. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4104. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4105. }
  4106. #endif
  4107. VkPhysicalDeviceMaintenance4Features maint4_features {};
  4108. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  4109. if (maintenance4_support) {
  4110. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  4111. last_struct = (VkBaseOutStructure *)&maint4_features;
  4112. device_extensions.push_back("VK_KHR_maintenance4");
  4113. }
  4114. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4115. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4116. if (device->integer_dot_product) {
  4117. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4118. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4119. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  4120. }
  4121. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  4122. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  4123. if (pipeline_executable_properties_support) {
  4124. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  4125. last_struct = (VkBaseOutStructure *)&pep_features;
  4126. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  4127. }
  4128. if (device->external_memory_host) {
  4129. device_extensions.push_back("VK_EXT_external_memory_host");
  4130. }
  4131. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  4132. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  4133. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  4134. #if defined(VK_KHR_shader_bfloat16)
  4135. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4136. #else
  4137. device->bf16 = false;
  4138. #endif
  4139. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  4140. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  4141. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  4142. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  4143. device->shader_int64 = device_features2.features.shaderInt64;
  4144. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  4145. device->vulkan_memory_model = vk12_features.vulkanMemoryModel;
  4146. if (device->subgroup_size_control) {
  4147. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  4148. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  4149. device_extensions.push_back("VK_EXT_subgroup_size_control");
  4150. }
  4151. device->subgroup_size_control = device->subgroup_size_control &&
  4152. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  4153. subgroup_size_control_features.subgroupSizeControl;
  4154. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  4155. #if defined(VK_KHR_cooperative_matrix)
  4156. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  4157. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  4158. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  4159. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  4160. device->subgroup_max_size >= 32;
  4161. #endif
  4162. if (coopmat2_support) {
  4163. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4164. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  4165. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  4166. coopmat2_features.cooperativeMatrixReductions &&
  4167. coopmat2_features.cooperativeMatrixConversions &&
  4168. coopmat2_features.cooperativeMatrixPerElementOperations &&
  4169. coopmat2_features.cooperativeMatrixTensorAddressing &&
  4170. coopmat2_features.cooperativeMatrixBlockLoads &&
  4171. vk12_features.bufferDeviceAddress) {
  4172. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  4173. uint32_t count = 0;
  4174. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  4175. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  4176. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  4177. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  4178. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  4179. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  4180. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  4181. flexible_dimensions.resize(count, empty_prop);
  4182. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  4183. bool found_fp16_128 = false,
  4184. found_fp16_256 = false,
  4185. found_fp32_128 = false,
  4186. found_fp32_256 = false;
  4187. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  4188. // with 32x16x16 and 256 with 32x32x16.
  4189. for (auto &prop : flexible_dimensions) {
  4190. if (prop.saturatingAccumulation == VK_FALSE &&
  4191. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  4192. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4193. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4194. if (prop.workgroupInvocations == 128 &&
  4195. prop.MGranularity <= 32 &&
  4196. prop.NGranularity <= 16 &&
  4197. prop.KGranularity <= 16) {
  4198. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4199. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4200. found_fp16_128 = true;
  4201. }
  4202. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4203. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4204. found_fp32_128 = true;
  4205. }
  4206. }
  4207. if (prop.workgroupInvocations == 256 &&
  4208. prop.MGranularity <= 32 &&
  4209. prop.NGranularity <= 32 &&
  4210. prop.KGranularity <= 16) {
  4211. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4212. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4213. found_fp16_256 = true;
  4214. }
  4215. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4216. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4217. found_fp32_256 = true;
  4218. }
  4219. }
  4220. }
  4221. }
  4222. if (found_fp16_128 && found_fp16_256 &&
  4223. found_fp32_128 && found_fp32_256 &&
  4224. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  4225. device->coopmat2 = true;
  4226. }
  4227. }
  4228. #endif
  4229. }
  4230. if (!vk11_features.storageBuffer16BitAccess) {
  4231. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  4232. throw std::runtime_error("Unsupported device");
  4233. }
  4234. device_extensions.push_back("VK_KHR_16bit_storage");
  4235. #ifdef GGML_VULKAN_VALIDATE
  4236. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  4237. #endif
  4238. if (device->fp16) {
  4239. device_extensions.push_back("VK_KHR_shader_float16_int8");
  4240. }
  4241. #if defined(VK_KHR_cooperative_matrix)
  4242. if (device->coopmat_support) {
  4243. // Query supported shapes
  4244. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  4245. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  4246. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  4247. uint32_t cm_props_num;
  4248. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  4249. cm_props.resize(cm_props_num);
  4250. for (auto& prop : cm_props) {
  4251. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  4252. }
  4253. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  4254. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  4255. for (auto& prop : cm_props) {
  4256. 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));
  4257. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  4258. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  4259. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4260. ) {
  4261. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  4262. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  4263. // coopmat sizes not set yet
  4264. if (device->coopmat_m == 0) {
  4265. device->coopmat_acc_f32_support = true;
  4266. device->coopmat_m = prop.MSize;
  4267. device->coopmat_n = prop.NSize;
  4268. device->coopmat_k = prop.KSize;
  4269. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4270. // Only enable if shape is identical
  4271. device->coopmat_acc_f32_support = true;
  4272. }
  4273. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4274. device->coopmat_support_16x16x16_f32acc = true;
  4275. }
  4276. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  4277. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  4278. // coopmat sizes not set yet
  4279. if (device->coopmat_m == 0) {
  4280. device->coopmat_acc_f16_support = true;
  4281. device->coopmat_m = prop.MSize;
  4282. device->coopmat_n = prop.NSize;
  4283. device->coopmat_k = prop.KSize;
  4284. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4285. // Only enable if shape is identical
  4286. device->coopmat_acc_f16_support = true;
  4287. }
  4288. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4289. device->coopmat_support_16x16x16_f16acc = true;
  4290. }
  4291. }
  4292. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  4293. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  4294. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  4295. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  4296. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  4297. device->coopmat_int_m == 0
  4298. ) {
  4299. device->coopmat_int_support = true;
  4300. device->coopmat_int_m = prop.MSize;
  4301. device->coopmat_int_n = prop.NSize;
  4302. device->coopmat_int_k = prop.KSize;
  4303. }
  4304. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4305. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4306. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4307. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4308. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4309. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4310. ) {
  4311. // coopmat sizes not set yet
  4312. if (device->coopmat_m == 0) {
  4313. device->coopmat_bf16_support = true;
  4314. device->coopmat_m = prop.MSize;
  4315. device->coopmat_n = prop.NSize;
  4316. device->coopmat_k = prop.KSize;
  4317. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4318. // Only enable if shape is identical
  4319. device->coopmat_bf16_support = true;
  4320. }
  4321. }
  4322. #endif
  4323. }
  4324. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  4325. // No suitable matmul mode found
  4326. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  4327. device->coopmat_support = false;
  4328. }
  4329. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4330. device->coopmat_bf16_support = false;
  4331. }
  4332. }
  4333. if (device->coopmat_support) {
  4334. device_extensions.push_back("VK_KHR_cooperative_matrix");
  4335. }
  4336. #if defined(VK_KHR_shader_bfloat16)
  4337. if (device->coopmat_bf16_support) {
  4338. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4339. }
  4340. #endif
  4341. #endif
  4342. device->name = GGML_VK_NAME + std::to_string(idx);
  4343. device_create_info = {
  4344. vk::DeviceCreateFlags(),
  4345. device_queue_create_infos,
  4346. {},
  4347. device_extensions
  4348. };
  4349. device_create_info.setPNext(&device_features2);
  4350. device->device = device->physical_device.createDevice(device_create_info);
  4351. // Queues
  4352. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  4353. // Shaders
  4354. // Disable matmul tile sizes early if performance low or not supported
  4355. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  4356. switch (device->vendor_id) {
  4357. #ifndef GGML_VULKAN_RUN_TESTS
  4358. case VK_VENDOR_ID_AMD:
  4359. device->mul_mat_l[i] = false;
  4360. device->mul_mat_m[i] = true;
  4361. device->mul_mat_s[i] = true;
  4362. device->mul_mat_id_l[i] = false;
  4363. device->mul_mat_id_m[i] = true;
  4364. device->mul_mat_id_s[i] = true;
  4365. break;
  4366. case VK_VENDOR_ID_INTEL:
  4367. if (!device->coopmat_support || device->architecture != INTEL_XE2) {
  4368. device->mul_mat_l[i] = false;
  4369. device->mul_mat_id_l[i] = false;
  4370. } else {
  4371. device->mul_mat_l[i] = true; // if coopmat & XE2+, allow large matmul warptile config for Intel
  4372. device->mul_mat_id_l[i] = true;
  4373. }
  4374. device->mul_mat_m[i] = true;
  4375. device->mul_mat_s[i] = true;
  4376. device->mul_mat_id_m[i] = true;
  4377. device->mul_mat_id_s[i] = true;
  4378. break;
  4379. case VK_VENDOR_ID_APPLE:
  4380. device->mul_mat_l[i] = false;
  4381. device->mul_mat_m[i] = true;
  4382. device->mul_mat_s[i] = false;
  4383. device->mul_mat_id_l[i] = false;
  4384. device->mul_mat_id_m[i] = true;
  4385. device->mul_mat_id_s[i] = false;
  4386. break;
  4387. #endif
  4388. default:
  4389. device->mul_mat_l[i] = true;
  4390. device->mul_mat_m[i] = true;
  4391. device->mul_mat_s[i] = true;
  4392. device->mul_mat_id_l[i] = true;
  4393. device->mul_mat_id_m[i] = true;
  4394. device->mul_mat_id_s[i] = true;
  4395. break;
  4396. }
  4397. }
  4398. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  4399. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  4400. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  4401. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  4402. dsl_binding_flags.push_back({});
  4403. }
  4404. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  4405. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  4406. {},
  4407. dsl_binding);
  4408. descriptor_set_layout_create_info.setPNext(&dslbfci);
  4409. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  4410. ggml_vk_load_shaders(device);
  4411. if (!device->single_queue) {
  4412. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  4413. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  4414. } else {
  4415. // TODO: Use pointer or reference to avoid copy
  4416. device->transfer_queue.copyFrom(device->compute_queue);
  4417. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  4418. }
  4419. device->buffer_type = {
  4420. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4421. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  4422. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  4423. };
  4424. device->fence = device->device.createFence({});
  4425. device->idx = idx;
  4426. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  4427. device->add_rms_fusion = !device->disable_fusion &&
  4428. device->subgroup_arithmetic &&
  4429. device->vendor_id != VK_VENDOR_ID_INTEL;
  4430. device->partials_binding_alignment =
  4431. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  4432. device->mmvq_mode = 0;
  4433. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  4434. device->mmvq_mode = -1;
  4435. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  4436. device->mmvq_mode = 1;
  4437. }
  4438. return device;
  4439. }
  4440. return vk_instance.devices[idx];
  4441. }
  4442. static void ggml_vk_print_gpu_info(size_t idx) {
  4443. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4444. size_t dev_num = vk_instance.device_indices[idx];
  4445. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4446. GGML_ASSERT(vk_instance_initialized);
  4447. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4448. if (dev_num >= devices.size()) {
  4449. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4450. throw std::runtime_error("Device not found");
  4451. }
  4452. vk::PhysicalDevice physical_device = devices[dev_num];
  4453. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4454. bool fp16_storage = false;
  4455. bool fp16_compute = false;
  4456. bool coopmat_support = false;
  4457. bool coopmat2_support = false;
  4458. bool integer_dot_product = false;
  4459. bool bfloat16_support = false;
  4460. for (auto properties : ext_props) {
  4461. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4462. fp16_storage = true;
  4463. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4464. fp16_compute = true;
  4465. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4466. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4467. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4468. coopmat_support = true;
  4469. #endif
  4470. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4471. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4472. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4473. coopmat2_support = true;
  4474. #endif
  4475. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4476. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4477. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4478. integer_dot_product = true;
  4479. #endif
  4480. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4481. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4482. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4483. bfloat16_support = true;
  4484. #endif
  4485. }
  4486. }
  4487. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4488. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4489. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4490. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4491. vk::PhysicalDeviceProperties2 props2;
  4492. vk::PhysicalDeviceMaintenance3Properties props3;
  4493. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4494. vk::PhysicalDeviceDriverProperties driver_props;
  4495. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4496. props2.pNext = &props3;
  4497. props3.pNext = &subgroup_props;
  4498. subgroup_props.pNext = &driver_props;
  4499. // Pointer to the last chain element
  4500. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4501. if (integer_dot_product) {
  4502. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4503. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4504. }
  4505. physical_device.getProperties2(&props2);
  4506. VkPhysicalDeviceFeatures2 device_features2;
  4507. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4508. device_features2.pNext = nullptr;
  4509. VkPhysicalDeviceVulkan11Features vk11_features;
  4510. vk11_features.pNext = nullptr;
  4511. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4512. device_features2.pNext = &vk11_features;
  4513. VkPhysicalDeviceVulkan12Features vk12_features;
  4514. vk12_features.pNext = nullptr;
  4515. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4516. vk11_features.pNext = &vk12_features;
  4517. // Pointer to the last chain element
  4518. last_struct = (VkBaseOutStructure *)&vk12_features;
  4519. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4520. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4521. coopmat_features.pNext = nullptr;
  4522. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4523. coopmat_features.cooperativeMatrix = VK_FALSE;
  4524. if (coopmat_support) {
  4525. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4526. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4527. }
  4528. #endif
  4529. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4530. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4531. if (integer_dot_product) {
  4532. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4533. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4534. }
  4535. #if defined(VK_KHR_shader_bfloat16)
  4536. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4537. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4538. if (bfloat16_support) {
  4539. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4540. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4541. }
  4542. #endif
  4543. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4544. fp16 = fp16 && vk12_features.shaderFloat16;
  4545. #if defined(VK_KHR_shader_bfloat16)
  4546. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4547. #else
  4548. bool bf16 = false;
  4549. #endif
  4550. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4551. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4552. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4553. integer_dot_product = integer_dot_product
  4554. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4555. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4556. coopmat_support = coopmat_support
  4557. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4558. && coopmat_features.cooperativeMatrix
  4559. #endif
  4560. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4561. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4562. std::string device_name = props2.properties.deviceName.data();
  4563. 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",
  4564. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4565. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4566. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4567. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4568. }
  4569. }
  4570. static bool ggml_vk_instance_layer_settings_available();
  4571. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4572. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4573. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4574. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4575. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4576. return ggml_vk_default_dispatcher_instance;
  4577. }
  4578. static void ggml_vk_instance_init() {
  4579. if (vk_instance_initialized) {
  4580. return;
  4581. }
  4582. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4583. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4584. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4585. uint32_t api_version = vk::enumerateInstanceVersion();
  4586. if (api_version < VK_API_VERSION_1_2) {
  4587. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4588. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4589. }
  4590. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4591. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4592. const bool layer_settings = ggml_vk_instance_layer_settings_available();
  4593. #ifdef __APPLE__
  4594. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4595. #endif
  4596. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4597. std::vector<const char*> layers;
  4598. if (layer_settings) {
  4599. layers.push_back("VK_LAYER_KHRONOS_validation");
  4600. }
  4601. std::vector<const char*> extensions;
  4602. if (layer_settings) {
  4603. extensions.push_back("VK_EXT_layer_settings");
  4604. }
  4605. #ifdef __APPLE__
  4606. if (portability_enumeration_ext) {
  4607. extensions.push_back("VK_KHR_portability_enumeration");
  4608. }
  4609. #endif
  4610. if (debug_utils_ext) {
  4611. extensions.push_back("VK_EXT_debug_utils");
  4612. }
  4613. VkBool32 enable_best_practice = layer_settings;
  4614. std::vector<vk::LayerSettingEXT> settings = {
  4615. {
  4616. "VK_LAYER_KHRONOS_validation",
  4617. "validate_best_practices",
  4618. vk::LayerSettingTypeEXT::eBool32,
  4619. 1,
  4620. &enable_best_practice
  4621. },
  4622. };
  4623. vk::LayerSettingsCreateInfoEXT layer_setting_info(settings);
  4624. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions, &layer_setting_info);
  4625. #ifdef __APPLE__
  4626. if (portability_enumeration_ext) {
  4627. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4628. }
  4629. #endif
  4630. vk_instance.instance = vk::createInstance(instance_create_info);
  4631. vk_instance_initialized = true;
  4632. if (debug_utils_ext) {
  4633. vk_instance.debug_utils_support = true;
  4634. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4635. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4636. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4637. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4638. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4639. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4640. }
  4641. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4642. vk_perf_logger_concurrent = getenv("GGML_VK_PERF_LOGGER_CONCURRENT") != nullptr;
  4643. vk_enable_sync_logger = getenv("GGML_VK_SYNC_LOGGER") != nullptr;
  4644. const char* GGML_VK_PERF_LOGGER_FREQUENCY = getenv("GGML_VK_PERF_LOGGER_FREQUENCY");
  4645. if (GGML_VK_PERF_LOGGER_FREQUENCY != nullptr) {
  4646. vk_perf_logger_frequency = std::stoul(GGML_VK_PERF_LOGGER_FREQUENCY);
  4647. }
  4648. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4649. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4650. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4651. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4652. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4653. if (devices_env != nullptr) {
  4654. size_t num_available_devices = devices.size();
  4655. std::string devices(devices_env);
  4656. std::replace(devices.begin(), devices.end(), ',', ' ');
  4657. std::stringstream ss(devices);
  4658. size_t tmp;
  4659. while (ss >> tmp) {
  4660. if(tmp >= num_available_devices) {
  4661. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4662. throw std::runtime_error("Invalid Vulkan device index");
  4663. }
  4664. vk_instance.device_indices.push_back(tmp);
  4665. }
  4666. } else {
  4667. // If no vulkan devices are found, return early
  4668. if (devices.empty()) {
  4669. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4670. return;
  4671. }
  4672. // Default to using all dedicated GPUs
  4673. for (size_t i = 0; i < devices.size(); i++) {
  4674. vk::PhysicalDeviceProperties2 new_props;
  4675. vk::PhysicalDeviceDriverProperties new_driver;
  4676. vk::PhysicalDeviceIDProperties new_id;
  4677. new_props.pNext = &new_driver;
  4678. new_driver.pNext = &new_id;
  4679. devices[i].getProperties2(&new_props);
  4680. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4681. // Check if there are two physical devices corresponding to the same GPU
  4682. auto old_device = std::find_if(
  4683. vk_instance.device_indices.begin(),
  4684. vk_instance.device_indices.end(),
  4685. [&devices, &new_id](const size_t k){
  4686. vk::PhysicalDeviceProperties2 old_props;
  4687. vk::PhysicalDeviceIDProperties old_id;
  4688. old_props.pNext = &old_id;
  4689. devices[k].getProperties2(&old_props);
  4690. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4691. equals = equals || (
  4692. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4693. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4694. );
  4695. return equals;
  4696. }
  4697. );
  4698. if (old_device == vk_instance.device_indices.end()) {
  4699. vk_instance.device_indices.push_back(i);
  4700. } else {
  4701. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4702. // This can cause error when splitting layers aross the devices, need to keep only 1
  4703. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4704. vk::PhysicalDeviceProperties2 old_props;
  4705. vk::PhysicalDeviceDriverProperties old_driver;
  4706. old_props.pNext = &old_driver;
  4707. devices[*old_device].getProperties2(&old_props);
  4708. std::map<vk::DriverId, int> driver_priorities {};
  4709. int old_priority = std::numeric_limits<int>::max();
  4710. int new_priority = std::numeric_limits<int>::max();
  4711. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4712. // Smaller number -> higher priority
  4713. switch (old_props.properties.vendorID) {
  4714. case VK_VENDOR_ID_AMD:
  4715. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4716. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4717. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4718. break;
  4719. case VK_VENDOR_ID_INTEL:
  4720. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4721. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4722. break;
  4723. case VK_VENDOR_ID_NVIDIA:
  4724. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4725. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4726. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4727. #endif
  4728. break;
  4729. }
  4730. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4731. if (driver_priorities.count(old_driver.driverID)) {
  4732. old_priority = driver_priorities[old_driver.driverID];
  4733. }
  4734. if (driver_priorities.count(new_driver.driverID)) {
  4735. new_priority = driver_priorities[new_driver.driverID];
  4736. }
  4737. if (new_priority < old_priority) {
  4738. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4739. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4740. vk_instance.device_indices.push_back(i);
  4741. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4742. }
  4743. else {
  4744. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4745. }
  4746. }
  4747. }
  4748. }
  4749. // If no GPUs found, fall back to the first non-CPU device.
  4750. // If only CPU devices are available, return without devices.
  4751. if (vk_instance.device_indices.empty()) {
  4752. for (size_t i = 0; i < devices.size(); i++) {
  4753. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4754. vk_instance.device_indices.push_back(i);
  4755. break;
  4756. }
  4757. }
  4758. }
  4759. if (vk_instance.device_indices.empty()) {
  4760. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4761. return;
  4762. }
  4763. }
  4764. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4765. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4766. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4767. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4768. bool membudget_supported = false;
  4769. for (const auto & ext : extensionprops) {
  4770. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4771. membudget_supported = true;
  4772. break;
  4773. }
  4774. }
  4775. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4776. ggml_vk_print_gpu_info(i);
  4777. }
  4778. }
  4779. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4780. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4781. ggml_vk_instance_init();
  4782. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4783. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4784. ctx->device = ggml_vk_get_device(idx);
  4785. ctx->semaphore_idx = 0;
  4786. ctx->event_idx = 0;
  4787. ctx->prealloc_size_x = 0;
  4788. ctx->prealloc_size_y = 0;
  4789. ctx->prealloc_size_split_k = 0;
  4790. // Fixed size of 1KB, for deterministic behavior
  4791. ctx->prealloc_size_add_rms_partials = 1024;
  4792. ctx->fence = ctx->device->device.createFence({});
  4793. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4794. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4795. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4796. if (vk_perf_logger_enabled) {
  4797. ctx->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  4798. }
  4799. #ifdef GGML_VULKAN_CHECK_RESULTS
  4800. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4801. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4802. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4803. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4804. #endif
  4805. }
  4806. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4807. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4808. switch (type) {
  4809. case GGML_TYPE_F32:
  4810. case GGML_TYPE_Q4_0:
  4811. case GGML_TYPE_Q4_1:
  4812. case GGML_TYPE_Q5_0:
  4813. case GGML_TYPE_Q5_1:
  4814. case GGML_TYPE_Q8_0:
  4815. case GGML_TYPE_Q2_K:
  4816. case GGML_TYPE_Q3_K:
  4817. case GGML_TYPE_Q4_K:
  4818. case GGML_TYPE_Q5_K:
  4819. case GGML_TYPE_Q6_K:
  4820. case GGML_TYPE_IQ1_S:
  4821. case GGML_TYPE_IQ1_M:
  4822. case GGML_TYPE_IQ2_XXS:
  4823. case GGML_TYPE_IQ2_XS:
  4824. case GGML_TYPE_IQ2_S:
  4825. case GGML_TYPE_IQ3_XXS:
  4826. case GGML_TYPE_IQ3_S:
  4827. case GGML_TYPE_IQ4_XS:
  4828. case GGML_TYPE_IQ4_NL:
  4829. case GGML_TYPE_MXFP4:
  4830. break;
  4831. default:
  4832. return nullptr;
  4833. }
  4834. return ctx->device->pipeline_dequant[type];
  4835. }
  4836. 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) {
  4837. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4838. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4839. return ctx->device->pipeline_matmul_f32;
  4840. }
  4841. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4842. return ctx->device->pipeline_matmul_f32_f16;
  4843. }
  4844. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4845. return ctx->device->pipeline_matmul_bf16;
  4846. }
  4847. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4848. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4849. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4850. }
  4851. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4852. return ctx->device->pipeline_matmul_f16.f16acc;
  4853. }
  4854. } else {
  4855. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4856. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4857. }
  4858. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4859. return ctx->device->pipeline_matmul_f16.f32acc;
  4860. }
  4861. }
  4862. // MMQ
  4863. if (src1_type == GGML_TYPE_Q8_1) {
  4864. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4865. if (pipelines->is_empty()) {
  4866. return nullptr;
  4867. }
  4868. return pipelines;
  4869. }
  4870. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4871. return nullptr;
  4872. }
  4873. switch (src0_type) {
  4874. case GGML_TYPE_Q4_0:
  4875. case GGML_TYPE_Q4_1:
  4876. case GGML_TYPE_Q5_0:
  4877. case GGML_TYPE_Q5_1:
  4878. case GGML_TYPE_Q8_0:
  4879. case GGML_TYPE_Q2_K:
  4880. case GGML_TYPE_Q3_K:
  4881. case GGML_TYPE_Q4_K:
  4882. case GGML_TYPE_Q5_K:
  4883. case GGML_TYPE_Q6_K:
  4884. case GGML_TYPE_IQ1_S:
  4885. case GGML_TYPE_IQ1_M:
  4886. case GGML_TYPE_IQ2_XXS:
  4887. case GGML_TYPE_IQ2_XS:
  4888. case GGML_TYPE_IQ2_S:
  4889. case GGML_TYPE_IQ3_XXS:
  4890. case GGML_TYPE_IQ3_S:
  4891. case GGML_TYPE_IQ4_XS:
  4892. case GGML_TYPE_IQ4_NL:
  4893. case GGML_TYPE_MXFP4:
  4894. break;
  4895. default:
  4896. return nullptr;
  4897. }
  4898. if (ctx->device->coopmat2) {
  4899. assert(src1_type == GGML_TYPE_F16);
  4900. 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;
  4901. }
  4902. if (ctx->device->coopmat_support) {
  4903. 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;
  4904. }
  4905. 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;
  4906. }
  4907. 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) {
  4908. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4909. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4910. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4911. if (b_type == GGML_TYPE_Q8_1) {
  4912. switch (a_type) {
  4913. case GGML_TYPE_Q4_0:
  4914. case GGML_TYPE_Q4_1:
  4915. case GGML_TYPE_Q5_0:
  4916. case GGML_TYPE_Q5_1:
  4917. case GGML_TYPE_Q8_0:
  4918. case GGML_TYPE_MXFP4:
  4919. case GGML_TYPE_Q2_K:
  4920. case GGML_TYPE_Q3_K:
  4921. case GGML_TYPE_Q4_K:
  4922. case GGML_TYPE_Q5_K:
  4923. case GGML_TYPE_Q6_K:
  4924. case GGML_TYPE_IQ1_S:
  4925. case GGML_TYPE_IQ1_M:
  4926. break;
  4927. default:
  4928. return nullptr;
  4929. }
  4930. }
  4931. switch (a_type) {
  4932. case GGML_TYPE_F32:
  4933. case GGML_TYPE_F16:
  4934. case GGML_TYPE_BF16:
  4935. case GGML_TYPE_Q4_0:
  4936. case GGML_TYPE_Q4_1:
  4937. case GGML_TYPE_Q5_0:
  4938. case GGML_TYPE_Q5_1:
  4939. case GGML_TYPE_Q8_0:
  4940. case GGML_TYPE_Q2_K:
  4941. case GGML_TYPE_Q3_K:
  4942. case GGML_TYPE_Q4_K:
  4943. case GGML_TYPE_Q5_K:
  4944. case GGML_TYPE_Q6_K:
  4945. case GGML_TYPE_IQ1_S:
  4946. case GGML_TYPE_IQ1_M:
  4947. case GGML_TYPE_IQ2_XXS:
  4948. case GGML_TYPE_IQ2_XS:
  4949. case GGML_TYPE_IQ2_S:
  4950. case GGML_TYPE_IQ3_XXS:
  4951. case GGML_TYPE_IQ3_S:
  4952. case GGML_TYPE_IQ4_XS:
  4953. case GGML_TYPE_IQ4_NL:
  4954. case GGML_TYPE_MXFP4:
  4955. break;
  4956. default:
  4957. return nullptr;
  4958. }
  4959. // heuristic to choose workgroup size
  4960. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4961. 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) {
  4962. // Prefer larger workgroups when M is small, to spread the work out more
  4963. // and keep more SMs busy.
  4964. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4965. if (a_type == GGML_TYPE_Q6_K) {
  4966. if (m < 4096 && k >= 1024) {
  4967. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4968. }
  4969. } else {
  4970. if (m <= 8192 && k >= 1024) {
  4971. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4972. }
  4973. }
  4974. }
  4975. if (b_type == GGML_TYPE_Q8_1) {
  4976. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4977. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4978. }
  4979. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4980. }
  4981. 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];
  4982. }
  4983. 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) {
  4984. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4985. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4986. return ctx->device->pipeline_matmul_id_f32;
  4987. }
  4988. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4989. return ctx->device->pipeline_matmul_id_bf16;
  4990. }
  4991. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4992. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4993. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4994. }
  4995. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4996. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4997. }
  4998. } else {
  4999. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  5000. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  5001. }
  5002. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  5003. return ctx->device->pipeline_matmul_id_f16.f32acc;
  5004. }
  5005. }
  5006. // MMQ
  5007. if (src1_type == GGML_TYPE_Q8_1) {
  5008. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  5009. if (pipelines->is_empty()) {
  5010. return nullptr;
  5011. }
  5012. return pipelines;
  5013. }
  5014. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  5015. switch (src0_type) {
  5016. case GGML_TYPE_Q4_0:
  5017. case GGML_TYPE_Q4_1:
  5018. case GGML_TYPE_Q5_0:
  5019. case GGML_TYPE_Q5_1:
  5020. case GGML_TYPE_Q8_0:
  5021. case GGML_TYPE_Q2_K:
  5022. case GGML_TYPE_Q3_K:
  5023. case GGML_TYPE_Q4_K:
  5024. case GGML_TYPE_Q5_K:
  5025. case GGML_TYPE_Q6_K:
  5026. case GGML_TYPE_IQ1_S:
  5027. case GGML_TYPE_IQ1_M:
  5028. case GGML_TYPE_IQ2_XXS:
  5029. case GGML_TYPE_IQ2_XS:
  5030. case GGML_TYPE_IQ2_S:
  5031. case GGML_TYPE_IQ3_XXS:
  5032. case GGML_TYPE_IQ3_S:
  5033. case GGML_TYPE_IQ4_XS:
  5034. case GGML_TYPE_IQ4_NL:
  5035. case GGML_TYPE_MXFP4:
  5036. break;
  5037. default:
  5038. return nullptr;
  5039. }
  5040. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  5041. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  5042. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  5043. bool support_fp16acc = !mmp.f16acc->is_empty();
  5044. bool support_fp32acc = !mmp.f32acc->is_empty();
  5045. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  5046. return mmp.f16acc;
  5047. } else {
  5048. GGML_ASSERT(support_fp32acc);
  5049. return mmp.f32acc;
  5050. }
  5051. }
  5052. 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) {
  5053. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  5054. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_Q8_1);
  5055. if (b_type == GGML_TYPE_Q8_1) {
  5056. switch (a_type) {
  5057. case GGML_TYPE_Q4_0:
  5058. case GGML_TYPE_Q4_1:
  5059. case GGML_TYPE_Q5_0:
  5060. case GGML_TYPE_Q5_1:
  5061. case GGML_TYPE_Q8_0:
  5062. case GGML_TYPE_MXFP4:
  5063. case GGML_TYPE_Q2_K:
  5064. case GGML_TYPE_Q3_K:
  5065. case GGML_TYPE_Q4_K:
  5066. case GGML_TYPE_Q5_K:
  5067. case GGML_TYPE_Q6_K:
  5068. case GGML_TYPE_IQ1_S:
  5069. case GGML_TYPE_IQ1_M:
  5070. break;
  5071. default:
  5072. return nullptr;
  5073. }
  5074. }
  5075. switch (a_type) {
  5076. case GGML_TYPE_F32:
  5077. case GGML_TYPE_F16:
  5078. case GGML_TYPE_BF16:
  5079. case GGML_TYPE_Q4_0:
  5080. case GGML_TYPE_Q4_1:
  5081. case GGML_TYPE_Q5_0:
  5082. case GGML_TYPE_Q5_1:
  5083. case GGML_TYPE_Q8_0:
  5084. case GGML_TYPE_Q2_K:
  5085. case GGML_TYPE_Q3_K:
  5086. case GGML_TYPE_Q4_K:
  5087. case GGML_TYPE_Q5_K:
  5088. case GGML_TYPE_Q6_K:
  5089. case GGML_TYPE_IQ1_S:
  5090. case GGML_TYPE_IQ1_M:
  5091. case GGML_TYPE_IQ2_XXS:
  5092. case GGML_TYPE_IQ2_XS:
  5093. case GGML_TYPE_IQ2_S:
  5094. case GGML_TYPE_IQ3_XXS:
  5095. case GGML_TYPE_IQ3_S:
  5096. case GGML_TYPE_IQ4_XS:
  5097. case GGML_TYPE_IQ4_NL:
  5098. case GGML_TYPE_MXFP4:
  5099. break;
  5100. default:
  5101. return nullptr;
  5102. }
  5103. // heuristic to choose workgroup size
  5104. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  5105. 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) {
  5106. // Prefer larger workgroups when M is small, to spread the work out more
  5107. // and keep more SMs busy.
  5108. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  5109. if (a_type == GGML_TYPE_Q6_K) {
  5110. if (m < 4096 && k >= 1024) {
  5111. dmmv_wg = DMMV_WG_SIZE_LARGE;
  5112. }
  5113. } else {
  5114. if (m <= 8192 && k >= 1024) {
  5115. dmmv_wg = DMMV_WG_SIZE_LARGE;
  5116. }
  5117. }
  5118. }
  5119. if (b_type == GGML_TYPE_Q8_1) {
  5120. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  5121. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  5122. }
  5123. return ctx->device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[dmmv_wg][a_type];
  5124. }
  5125. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[dmmv_wg][a_type];
  5126. }
  5127. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  5128. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  5129. vk_buffer buf = ggml_vk_create_buffer(device, size,
  5130. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5131. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  5132. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  5133. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  5134. size/1024.0/1024.0);
  5135. device->device.freeMemory(buf->device_memory);
  5136. device->device.destroyBuffer(buf->buffer);
  5137. return nullptr;
  5138. }
  5139. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5140. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  5141. return buf->ptr;
  5142. }
  5143. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  5144. if (ptr == nullptr) {
  5145. return;
  5146. }
  5147. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  5148. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5149. vk_buffer buf;
  5150. size_t index;
  5151. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  5152. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  5153. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  5154. if (ptr >= addr && ptr < endr) {
  5155. buf = std::get<2>(device->pinned_memory[i]);
  5156. index = i;
  5157. break;
  5158. }
  5159. }
  5160. if (buf == nullptr) {
  5161. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  5162. return;
  5163. }
  5164. ggml_vk_destroy_buffer(buf);
  5165. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  5166. }
  5167. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  5168. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5169. buf = nullptr;
  5170. buf_offset = 0;
  5171. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  5172. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  5173. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  5174. if (ptr >= addr && ptr < endr) {
  5175. buf = std::get<2>(device->pinned_memory[i]);
  5176. buf_offset = ((const uint8_t *)ptr) - addr;
  5177. break;
  5178. }
  5179. }
  5180. }
  5181. static vk_subbuffer ggml_vk_tensor_subbuffer(
  5182. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  5183. vk_buffer buffer = nullptr;
  5184. size_t offset = 0;
  5185. if (ctx->device->uma) {
  5186. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  5187. }
  5188. if (!buffer) {
  5189. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  5190. buffer = buf_ctx->dev_buffer;
  5191. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  5192. }
  5193. GGML_ASSERT(buffer != nullptr);
  5194. size_t size = ggml_nbytes(tensor);
  5195. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  5196. // The shader must support misaligned offsets when indexing into the buffer
  5197. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  5198. offset &= ~misalign_bytes;
  5199. size += misalign_bytes;
  5200. return vk_subbuffer{buffer, offset, size};
  5201. }
  5202. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  5203. vk_submission s;
  5204. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  5205. if (one_time) {
  5206. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  5207. } else {
  5208. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  5209. }
  5210. return s;
  5211. }
  5212. template <typename T> size_t push_constant_size(const T &t) {
  5213. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5214. GGML_UNUSED(t);
  5215. return sizeof(T);
  5216. }
  5217. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  5218. GGML_UNUSED(t);
  5219. return sizeof(T) * t.size();
  5220. }
  5221. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  5222. GGML_UNUSED(t);
  5223. return sizeof(T) * N;
  5224. }
  5225. template <typename T> const T *push_constant_data(const T &t) {
  5226. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5227. return &t;
  5228. }
  5229. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  5230. return t.data();
  5231. }
  5232. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  5233. return t.data();
  5234. }
  5235. template <typename T>
  5236. 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) {
  5237. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  5238. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  5239. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  5240. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  5241. for (auto& buffer : descriptor_buffer_infos) {
  5242. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  5243. }
  5244. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  5245. GGML_ASSERT(wg0 <= ctx->device->properties.limits.maxComputeWorkGroupCount[0] &&
  5246. wg1 <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] &&
  5247. wg2 <= ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  5248. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  5249. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  5250. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  5251. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  5252. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  5253. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  5254. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  5255. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  5256. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  5257. pipeline->layout,
  5258. 0,
  5259. { descriptor_set },
  5260. {});
  5261. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  5262. }
  5263. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  5264. s.buffer.end();
  5265. s.wait_semaphores = std::move(wait_semaphores);
  5266. s.signal_semaphores = std::move(signal_semaphores);
  5267. }
  5268. static void ggml_vk_ctx_end(vk_context& ctx) {
  5269. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  5270. if (ctx->s == nullptr) {
  5271. return;
  5272. }
  5273. ctx->s->buffer.end();
  5274. ctx->s = nullptr;
  5275. }
  5276. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  5277. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  5278. if (subctx->s != nullptr) {
  5279. ggml_vk_ctx_end(subctx);
  5280. }
  5281. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  5282. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  5283. }
  5284. static size_t ggml_vk_align_size(size_t width, size_t align) {
  5285. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  5286. return CEIL_DIV(width, align) * align;
  5287. }
  5288. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  5289. if (memcpys == nullptr) {
  5290. memcpy(dst, src, size);
  5291. } else {
  5292. memcpys->emplace_back(dst, src, size);
  5293. }
  5294. }
  5295. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  5296. if (memsets == nullptr) {
  5297. memset(dst, val, size);
  5298. } else {
  5299. memsets->emplace_back(dst, val, size);
  5300. }
  5301. }
  5302. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  5303. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  5304. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5305. ggml_vk_destroy_buffer(device->sync_staging);
  5306. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  5307. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5308. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5309. }
  5310. }
  5311. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  5312. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  5313. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5314. ggml_vk_destroy_buffer(ctx->sync_staging);
  5315. ctx->sync_staging = ggml_vk_create_buffer_check(ctx->device, size,
  5316. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5317. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5318. }
  5319. }
  5320. 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) {
  5321. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  5322. GGML_ASSERT(!ggml_is_contiguous(tensor));
  5323. // Buffer is already mapped
  5324. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5325. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5326. GGML_ABORT("fatal error");
  5327. }
  5328. // Check if src is pinned memory
  5329. vk_buffer buf = nullptr;
  5330. size_t buf_offset = 0;
  5331. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  5332. const uint64_t ne0 = tensor->ne[0];
  5333. const uint64_t ne1 = tensor->ne[1];
  5334. const uint64_t ne2 = tensor->ne[2];
  5335. const uint64_t ne3 = tensor->ne[3];
  5336. const uint64_t nb0 = tensor->nb[0];
  5337. const uint64_t nb1 = tensor->nb[1];
  5338. const uint64_t nb2 = tensor->nb[2];
  5339. const uint64_t nb3 = tensor->nb[3];
  5340. const ggml_type type = tensor->type;
  5341. const uint64_t ts = ggml_type_size(type);
  5342. const uint64_t bs = ggml_blck_size(type);
  5343. const uint64_t dstnb0 = ts;
  5344. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  5345. const uint64_t dstnb2 = dstnb1*ne1;
  5346. const uint64_t dstnb3 = dstnb2*ne2;
  5347. const uint64_t ne = ggml_nelements(tensor);
  5348. if (buf != nullptr) {
  5349. // Memory is pinned, use as staging buffer
  5350. std::vector<vk::BufferCopy> slices;
  5351. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5352. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5353. // Find longest contiguous slice
  5354. if (ne1*nb1 == dstnb2) {
  5355. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  5356. } else {
  5357. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5358. if (ne0*nb0/bs == dstnb1) {
  5359. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  5360. } else {
  5361. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5362. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5363. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5364. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  5365. }
  5366. }
  5367. }
  5368. }
  5369. }
  5370. }
  5371. ggml_vk_sync_buffers(ctx, subctx);
  5372. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5373. return;
  5374. }
  5375. if (!sync_staging) {
  5376. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5377. }
  5378. // Staging buffer required
  5379. vk_buffer& staging = ctx->device->sync_staging;
  5380. const uint64_t copy_size = ts*ne/bs;
  5381. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  5382. VkBufferCopy buf_copy{ 0, offset, copy_size };
  5383. ggml_vk_sync_buffers(ctx, subctx);
  5384. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5385. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5386. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5387. // Find longest contiguous slice
  5388. if (ne1*nb1 == dstnb2) {
  5389. 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);
  5390. } else {
  5391. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5392. if (ne0*nb0/bs == dstnb1) {
  5393. 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);
  5394. } else {
  5395. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5396. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5397. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5398. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  5399. }
  5400. }
  5401. }
  5402. }
  5403. }
  5404. }
  5405. }
  5406. static bool 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) {
  5407. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  5408. // Check if src is pinned memory
  5409. vk_buffer buf = nullptr;
  5410. size_t buf_offset = 0;
  5411. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  5412. if (buf != nullptr) {
  5413. // Memory is pinned, use as staging buffer
  5414. std::vector<vk::BufferCopy> slices(1);
  5415. if (width == spitch) {
  5416. // Only do single write if stride is equal
  5417. slices[0].srcOffset = buf_offset;
  5418. slices[0].dstOffset = offset;
  5419. slices[0].size = width * height;
  5420. } else {
  5421. slices.resize(height);
  5422. for (size_t i = 0; i < height; i++) {
  5423. slices[i].srcOffset = buf_offset + i * spitch;
  5424. slices[i].dstOffset = offset + i * width;
  5425. slices[i].size = width;
  5426. }
  5427. }
  5428. ggml_vk_sync_buffers(nullptr, subctx);
  5429. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5430. return true;
  5431. }
  5432. VK_LOG_DEBUG("STAGING");
  5433. if (!sync_staging) {
  5434. // copy was not handled caller needs to fall back
  5435. return false;
  5436. }
  5437. // Staging buffer required
  5438. const size_t copy_size = width*height;
  5439. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  5440. vk_buffer& staging_buffer = dst->device->sync_staging;
  5441. VkBufferCopy buf_copy = {
  5442. 0,
  5443. offset,
  5444. copy_size};
  5445. ggml_vk_sync_buffers(nullptr, subctx);
  5446. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5447. if (width == spitch) {
  5448. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  5449. } else {
  5450. for (size_t i = 0; i < height; i++) {
  5451. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  5452. }
  5453. }
  5454. return true;
  5455. }
  5456. static bool ggml_vk_buffer_write_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  5457. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  5458. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  5459. }
  5460. 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) {
  5461. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  5462. // Buffer is already mapped
  5463. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5464. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5465. for (size_t i = 0; i < height; i++) {
  5466. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  5467. }
  5468. } else {
  5469. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5470. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5471. ggml_vk_ctx_begin(dst->device, subctx);
  5472. bool ret = ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  5473. GGML_ASSERT(ret);
  5474. ggml_vk_ctx_end(subctx);
  5475. for (auto& cpy : subctx->in_memcpys) {
  5476. memcpy(cpy.dst, cpy.src, cpy.n);
  5477. }
  5478. for (auto& mset : subctx->memsets) {
  5479. memset(mset.dst, mset.val, mset.n);
  5480. }
  5481. ggml_vk_submit(subctx, dst->device->fence);
  5482. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  5483. dst->device->device.resetFences({ dst->device->fence });
  5484. ggml_vk_queue_command_pools_cleanup(dst->device);
  5485. }
  5486. }
  5487. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  5488. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  5489. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  5490. }
  5491. 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) {
  5492. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  5493. GGML_ASSERT(width > 0);
  5494. GGML_ASSERT(height > 0);
  5495. GGML_ASSERT(src != nullptr);
  5496. // TODO: staging_offset is not used
  5497. // Check if dst is pinned memory
  5498. vk_buffer buf = nullptr;
  5499. size_t buf_offset = 0;
  5500. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  5501. std::vector<vk::BufferCopy> slices(1);
  5502. if (width == spitch && width == dpitch) {
  5503. // Only do single write if stride is equal
  5504. slices[0].srcOffset = offset;
  5505. slices[0].dstOffset = buf_offset;
  5506. slices[0].size = width * height;
  5507. } else {
  5508. slices.resize(height);
  5509. for (size_t i = 0; i < height; i++) {
  5510. slices[i].srcOffset = offset + i * spitch;
  5511. slices[i].dstOffset = buf_offset + i * dpitch;
  5512. slices[i].size = width;
  5513. }
  5514. }
  5515. if (buf != nullptr) {
  5516. // Memory is pinned, use as staging buffer
  5517. ggml_vk_sync_buffers(nullptr, subctx);
  5518. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5519. return true;
  5520. }
  5521. VK_LOG_DEBUG("STAGING");
  5522. if (!sync_staging) {
  5523. // copy was not handled caller needs to fall back
  5524. return false;
  5525. }
  5526. // Fall back to staging buffer
  5527. const size_t copy_size = dpitch * height;
  5528. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5529. vk_buffer& staging_buffer = src->device->sync_staging;
  5530. ggml_vk_sync_buffers(nullptr, subctx);
  5531. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5532. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5533. return true;
  5534. }
  5535. 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) {
  5536. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5537. }
  5538. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5539. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5540. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5541. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5542. // the HW device to host copy path.
  5543. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5544. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5545. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5546. } else {
  5547. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5548. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5549. ggml_vk_ctx_begin(src->device, subctx);
  5550. bool ret = ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5551. GGML_ASSERT(ret);
  5552. ggml_vk_ctx_end(subctx);
  5553. ggml_vk_submit(subctx, src->device->fence);
  5554. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5555. src->device->device.resetFences({ src->device->fence });
  5556. ggml_vk_queue_command_pools_cleanup(src->device);
  5557. for (auto& cpy : subctx->out_memcpys) {
  5558. memcpy(cpy.dst, cpy.src, cpy.n);
  5559. }
  5560. }
  5561. }
  5562. 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) {
  5563. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5564. // Make sure both buffers are on same device
  5565. GGML_ASSERT(src->device == dst->device);
  5566. VkBufferCopy bc{ src_offset, dst_offset, size };
  5567. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5568. }
  5569. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5570. if (src->device == dst->device) {
  5571. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5572. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5573. // Copy within the device
  5574. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5575. ggml_vk_ctx_begin(src->device, subctx);
  5576. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5577. ggml_vk_ctx_end(subctx);
  5578. ggml_vk_submit(subctx, src->device->fence);
  5579. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5580. src->device->device.resetFences({ src->device->fence });
  5581. ggml_vk_queue_command_pools_cleanup(src->device);
  5582. } else {
  5583. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5584. // Copy device to device
  5585. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5586. // Copy to src staging buffer
  5587. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5588. // Copy to dst buffer
  5589. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5590. }
  5591. }
  5592. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5593. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5594. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5595. dst->device->uma) {
  5596. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5597. return;
  5598. }
  5599. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5600. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5601. }
  5602. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5603. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5604. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5605. dst->device->uma) {
  5606. memset((uint8_t*)dst->ptr + offset, c, size);
  5607. return;
  5608. }
  5609. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5610. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5611. ggml_vk_ctx_begin(dst->device, subctx);
  5612. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5613. ggml_vk_ctx_end(subctx);
  5614. ggml_vk_submit(subctx, dst->device->fence);
  5615. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5616. dst->device->device.resetFences({ dst->device->fence });
  5617. ggml_vk_queue_command_pools_cleanup(dst->device);
  5618. }
  5619. 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) {
  5620. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5621. if (disable_split_k) {
  5622. return 1;
  5623. }
  5624. uint32_t split_k = 1;
  5625. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5626. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5627. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5628. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5629. if (k >= 2048) {
  5630. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5631. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5632. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5633. split_k = 3;
  5634. }
  5635. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5636. split_k = std::min(split_k, 8u);
  5637. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5638. // If this rounded up size would cause the last split to be empty,
  5639. // then reduce the split count.
  5640. while (true) {
  5641. if (split_k == 1) {
  5642. break;
  5643. }
  5644. uint32_t k_split = CEIL_DIV(k, split_k);
  5645. k_split = ROUNDUP_POW2(k_split, 256);
  5646. if (k_split * (split_k - 1) < k) {
  5647. break;
  5648. }
  5649. split_k--;
  5650. }
  5651. }
  5652. }
  5653. return split_k;
  5654. }
  5655. 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) {
  5656. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5657. if (ctx->device->coopmat2) {
  5658. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5659. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5660. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5661. // Use large shader when the N dimension is greater than the medium shader's tile size
  5662. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5663. // Prefer large over medium if either:
  5664. // - medium or large tiles would overfill the GPU
  5665. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5666. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5667. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5668. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5669. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5670. 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])) {
  5671. return aligned ? mmp->a_l : mmp->l;
  5672. }
  5673. // Use medium shader when the N dimension is greater than the small shader's tile size
  5674. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5675. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5676. return aligned ? mmp->a_m : mmp->m;
  5677. }
  5678. return aligned ? mmp->a_s : mmp->s;
  5679. }
  5680. 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])) {
  5681. return aligned ? mmp->a_s : mmp->s;
  5682. }
  5683. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5684. return aligned ? mmp->a_m : mmp->m;
  5685. }
  5686. return aligned ? mmp->a_l : mmp->l;
  5687. GGML_UNUSED(src1_type);
  5688. }
  5689. 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) {
  5690. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5691. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5692. }
  5693. static void ggml_vk_matmul(
  5694. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5695. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5696. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5697. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5698. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5699. uint32_t padded_n) {
  5700. 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 << ")");
  5701. if (split_k == 1) {
  5702. 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 };
  5703. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5704. return;
  5705. }
  5706. if (ctx->prealloc_split_k_need_sync) {
  5707. ggml_vk_sync_buffers(ctx, subctx);
  5708. }
  5709. GGML_ASSERT(batch_stride_d == m * n);
  5710. // Round the split size up to a multiple of 256 (k-quant alignment)
  5711. uint32_t k_split = CEIL_DIV(k, split_k);
  5712. k_split = ROUNDUP_POW2(k_split, 256);
  5713. 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 };
  5714. // Make sure enough workgroups get assigned for split k to work
  5715. 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 });
  5716. ggml_vk_sync_buffers(ctx, subctx);
  5717. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5718. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5719. ctx->prealloc_split_k_need_sync = true;
  5720. }
  5721. 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) {
  5722. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5723. if (ctx->device->coopmat2) {
  5724. // Use large shader when the N dimension is greater than the medium shader's tile size
  5725. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5726. 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])) {
  5727. return aligned ? mmp->a_l : mmp->l;
  5728. }
  5729. // Use medium shader when the N dimension is greater than the small shader's tile size
  5730. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5731. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5732. return aligned ? mmp->a_m : mmp->m;
  5733. }
  5734. return aligned ? mmp->a_s : mmp->s;
  5735. }
  5736. 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])) {
  5737. return aligned ? mmp->a_s : mmp->s;
  5738. }
  5739. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5740. return aligned ? mmp->a_m : mmp->m;
  5741. }
  5742. return aligned ? mmp->a_l : mmp->l;
  5743. }
  5744. 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) {
  5745. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5746. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5747. }
  5748. static void ggml_vk_matmul_id(
  5749. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5750. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids, const vk_subbuffer & expert_count_buf,
  5751. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5752. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5753. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5754. uint32_t padded_n) {
  5755. 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 << "), expert_count: (" << expert_count_buf.buffer->buffer << ", " << expert_count_buf.offset << ", " << expert_count_buf.size << "), " <<
  5756. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5757. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5758. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5759. 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,
  5760. nei0, nei1, nbi1, ne11, padded_n };
  5761. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids, expert_count_buf }, pc, { m, nei1, n_as });
  5762. }
  5763. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5764. return
  5765. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5766. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5767. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5768. }
  5769. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5770. // Choose "contiguous copy" shader if src/dst are contiguous
  5771. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5772. // Use optimized "transpose" shader if src dim1 is the innermost dimension.
  5773. bool transpose = dst && src->nb[1] == ggml_type_size(to) && ggml_are_same_shape(dst, src);
  5774. if (transpose && src->type == to) {
  5775. if (ggml_type_size(to) == 4) {
  5776. return ctx->device->pipeline_cpy_transpose_32;
  5777. } else if (ggml_type_size(to) == 2) {
  5778. return ctx->device->pipeline_cpy_transpose_16;
  5779. }
  5780. }
  5781. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5782. if (contig) {
  5783. return ctx->device->pipeline_contig_cpy_f32_f32;
  5784. } else {
  5785. return ctx->device->pipeline_cpy_f32_f32;
  5786. }
  5787. }
  5788. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5789. if (contig) {
  5790. return ctx->device->pipeline_contig_cpy_f32_f16;
  5791. } else {
  5792. return ctx->device->pipeline_cpy_f32_f16;
  5793. }
  5794. }
  5795. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5796. if (contig) {
  5797. return ctx->device->pipeline_contig_cpy_f16_f16;
  5798. } else {
  5799. return ctx->device->pipeline_cpy_f16_f16;
  5800. }
  5801. }
  5802. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5803. if (contig) {
  5804. return ctx->device->pipeline_contig_cpy_f16_f32;
  5805. } else {
  5806. return ctx->device->pipeline_cpy_f16_f32;
  5807. }
  5808. }
  5809. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5810. if (contig) {
  5811. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5812. } else {
  5813. return ctx->device->pipeline_cpy_f32_bf16;
  5814. }
  5815. }
  5816. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5817. if (contig) {
  5818. return ctx->device->pipeline_contig_cpy_f32_i32;
  5819. } else {
  5820. return ctx->device->pipeline_cpy_f32_i32;
  5821. }
  5822. }
  5823. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5824. if (contig) {
  5825. return ctx->device->pipeline_contig_cpy_i32_f32;
  5826. } else {
  5827. return ctx->device->pipeline_cpy_i32_f32;
  5828. }
  5829. }
  5830. if (src->type == GGML_TYPE_F32) {
  5831. switch (to) {
  5832. case GGML_TYPE_Q4_0:
  5833. case GGML_TYPE_Q4_1:
  5834. case GGML_TYPE_Q5_0:
  5835. case GGML_TYPE_Q5_1:
  5836. case GGML_TYPE_Q8_0:
  5837. case GGML_TYPE_IQ4_NL:
  5838. return ctx->device->pipeline_cpy_f32_quant[to];
  5839. default:
  5840. break;
  5841. }
  5842. }
  5843. if (to == GGML_TYPE_F32) {
  5844. switch (src->type) {
  5845. case GGML_TYPE_Q4_0:
  5846. case GGML_TYPE_Q4_1:
  5847. case GGML_TYPE_Q5_0:
  5848. case GGML_TYPE_Q5_1:
  5849. case GGML_TYPE_Q8_0:
  5850. case GGML_TYPE_IQ4_NL:
  5851. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5852. default:
  5853. break;
  5854. }
  5855. }
  5856. if (src->type == to) {
  5857. // Copy two or four bytes at a time, depending on block size.
  5858. // For quantized types, we scale by block size/type size. But
  5859. // this path is also used for bf16->bf16 for example, where the
  5860. // type size must be exactly 2 or 4.
  5861. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5862. if ((ggml_type_size(src->type) % 4) == 0) {
  5863. if (contig) {
  5864. return ctx->device->pipeline_contig_cpy_f32_f32;
  5865. } else {
  5866. return ctx->device->pipeline_cpy_f32_f32;
  5867. }
  5868. } else {
  5869. if (contig) {
  5870. return ctx->device->pipeline_contig_cpy_f16_f16;
  5871. } else {
  5872. return ctx->device->pipeline_cpy_f16_f16;
  5873. }
  5874. }
  5875. }
  5876. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5877. GGML_ABORT("fatal error");
  5878. }
  5879. 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) {
  5880. 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] << "), ";
  5881. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5882. const int tensor_type_size = ggml_type_size(tensor->type);
  5883. const uint32_t ne = ggml_nelements(tensor);
  5884. std::array<uint32_t, 3> elements;
  5885. if (ne > 262144) {
  5886. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5887. } else if (ne > 512) {
  5888. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5889. } else {
  5890. elements = { ne, 1, 1 };
  5891. }
  5892. vk_op_unary_push_constants pc = {
  5893. (uint32_t)ne,
  5894. (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,
  5895. (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]),
  5896. 0,
  5897. 0.0f, 0.0f,
  5898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5899. };
  5900. init_pushconst_fastdiv(pc);
  5901. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5902. ggml_vk_sync_buffers(ctx, subctx);
  5903. }
  5904. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5905. switch(type) {
  5906. case GGML_TYPE_Q8_1:
  5907. return ctx->device->pipeline_quantize_q8_1_x4;
  5908. default:
  5909. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5910. GGML_ABORT("fatal error");
  5911. }
  5912. }
  5913. 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) {
  5914. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5915. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5916. const uint32_t num_blocks = CEIL_DIV(ne, pipeline->wg_denoms[0]);
  5917. // clamp the number of elements to the max workgroup count. The shader will iterate over the total number of blocks.
  5918. const uint64_t max_elements = std::min<uint64_t>(uint64_t{ctx->device->properties.limits.maxComputeWorkGroupCount[0]} * pipeline->wg_denoms[0], std::numeric_limits<uint32_t>::max());
  5919. const uint32_t elements = std::min(ne, static_cast<uint32_t>(max_elements));
  5920. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 2>{ ne, num_blocks }, { elements, 1, 1 });
  5921. ggml_vk_sync_buffers(ctx, subctx);
  5922. }
  5923. 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) {
  5924. 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];
  5925. 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];
  5926. 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];
  5927. std::cerr << "))");
  5928. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5929. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5930. const uint64_t ne00 = src0->ne[0];
  5931. const uint64_t ne01 = src0->ne[1];
  5932. const uint64_t ne02 = src0->ne[2];
  5933. const uint64_t ne03 = src0->ne[3];
  5934. const uint64_t ne10 = src1->ne[0];
  5935. const uint64_t ne11 = src1->ne[1];
  5936. const uint64_t ne12 = src1->ne[2];
  5937. const uint64_t ne13 = src1->ne[3];
  5938. const uint64_t ne21 = dst->ne[1];
  5939. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5940. const uint32_t stride_batch_d = stride_d*ne21;
  5941. const uint64_t r2 = ne12 / ne02;
  5942. const uint64_t r3 = ne13 / ne03;
  5943. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5944. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5945. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5946. vk_buffer d_Qx = nullptr;
  5947. size_t qx_buf_offset = 0;
  5948. vk_buffer d_Qy = nullptr;
  5949. size_t qy_buf_offset = 0;
  5950. bool src0_uma = false;
  5951. bool src1_uma = false;
  5952. if (ctx->device->uma) {
  5953. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5954. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5955. src0_uma = d_Qx != nullptr;
  5956. src1_uma = d_Qy != nullptr;
  5957. }
  5958. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5959. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5960. !ggml_vk_dim01_contiguous(src0);
  5961. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5962. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5963. !ggml_vk_dim01_contiguous(src1);
  5964. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5965. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5966. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5967. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  5968. // Check for mmq first
  5969. 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;
  5970. if (mmp == nullptr) {
  5971. // Fall back to f16 dequant mul mat
  5972. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5973. quantize_y = false;
  5974. }
  5975. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5976. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5977. if (qx_needs_dequant) {
  5978. // Fall back to dequant + f16 mulmat
  5979. 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]);
  5980. }
  5981. // Not implemented
  5982. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5983. 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)));
  5984. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5985. 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));
  5986. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5987. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5988. const uint64_t x_ne = ggml_nelements(src0);
  5989. // 128 elements per Q8_1 x4 block
  5990. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  5991. const uint64_t d_ne = ggml_nelements(dst);
  5992. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5993. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5994. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5995. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5996. 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);
  5997. const uint64_t d_sz = sizeof(float) * d_ne;
  5998. vk_pipeline to_fp16_vk_0 = nullptr;
  5999. vk_pipeline to_fp16_vk_1 = nullptr;
  6000. vk_pipeline to_q8_1 = nullptr;
  6001. if (x_non_contig) {
  6002. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6003. } else {
  6004. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6005. }
  6006. if (y_non_contig) {
  6007. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6008. } else {
  6009. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6010. }
  6011. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6012. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6013. if (quantize_y) {
  6014. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6015. }
  6016. {
  6017. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  6018. if (
  6019. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6020. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6021. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  6022. GGML_ABORT("Requested preallocation size is too large");
  6023. }
  6024. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6025. ctx->prealloc_size_x = x_sz;
  6026. ggml_vk_preallocate_buffers(ctx, subctx);
  6027. }
  6028. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6029. ctx->prealloc_size_y = y_sz;
  6030. ggml_vk_preallocate_buffers(ctx, subctx);
  6031. }
  6032. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  6033. ctx->prealloc_size_split_k = split_k_size;
  6034. ggml_vk_preallocate_buffers(ctx, subctx);
  6035. }
  6036. // Request descriptor sets
  6037. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6038. if (qx_needs_dequant) {
  6039. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6040. }
  6041. if (qy_needs_dequant) {
  6042. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6043. }
  6044. if (quantize_y) {
  6045. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6046. }
  6047. if (split_k > 1) {
  6048. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  6049. }
  6050. }
  6051. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6052. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6053. GGML_ASSERT(d_D != nullptr);
  6054. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  6055. vk_buffer d_X;
  6056. uint64_t x_buf_offset = 0;
  6057. vk_buffer d_Y;
  6058. uint64_t y_buf_offset = 0;
  6059. if (!src0_uma) {
  6060. d_Qx = src0_buf_ctx->dev_buffer;
  6061. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6062. GGML_ASSERT(d_Qx != nullptr);
  6063. }
  6064. if (!src1_uma) {
  6065. d_Qy = src1_buf_ctx->dev_buffer;
  6066. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6067. GGML_ASSERT(d_Qy != nullptr);
  6068. }
  6069. if (qx_needs_dequant) {
  6070. d_X = ctx->prealloc_x;
  6071. GGML_ASSERT(d_X->size >= x_sz);
  6072. } else {
  6073. d_X = d_Qx;
  6074. x_buf_offset = qx_buf_offset;
  6075. GGML_ASSERT(qx_sz == x_sz);
  6076. }
  6077. if (qy_needs_dequant) {
  6078. d_Y = ctx->prealloc_y;
  6079. GGML_ASSERT(d_Y->size >= y_sz);
  6080. } else if (quantize_y) {
  6081. d_Y = ctx->prealloc_y;
  6082. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6083. } else {
  6084. d_Y = d_Qy;
  6085. y_buf_offset = qy_buf_offset;
  6086. GGML_ASSERT(qy_sz == y_sz);
  6087. }
  6088. if (x_non_contig || qx_needs_dequant) {
  6089. if (ctx->prealloc_x_need_sync) {
  6090. ggml_vk_sync_buffers(ctx, subctx);
  6091. }
  6092. }
  6093. if (x_non_contig) {
  6094. 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));
  6095. } else if (qx_needs_dequant) {
  6096. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6097. 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});
  6098. ggml_vk_sync_buffers(ctx, subctx);
  6099. }
  6100. if (y_non_contig) {
  6101. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6102. ctx->prealloc_y_last_tensor_used != src1) {
  6103. if (ctx->prealloc_y_need_sync) {
  6104. ggml_vk_sync_buffers(ctx, subctx);
  6105. }
  6106. 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));
  6107. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6108. ctx->prealloc_y_last_tensor_used = src1;
  6109. }
  6110. }
  6111. if (quantize_y) {
  6112. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6113. ctx->prealloc_y_last_tensor_used != src1) {
  6114. if (ctx->prealloc_y_need_sync) {
  6115. ggml_vk_sync_buffers(ctx, subctx);
  6116. }
  6117. 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);
  6118. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6119. ctx->prealloc_y_last_tensor_used = src1;
  6120. }
  6121. }
  6122. uint32_t stride_batch_x = ne00*ne01;
  6123. uint32_t stride_batch_y = ne10*ne11;
  6124. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6125. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6126. }
  6127. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6128. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6129. }
  6130. // compute
  6131. ggml_vk_matmul(
  6132. ctx, subctx, pipeline,
  6133. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6134. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  6135. ne01, ne11, ne10,
  6136. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  6137. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  6138. ); // NOLINT
  6139. if (x_non_contig || qx_needs_dequant) {
  6140. ctx->prealloc_x_need_sync = true;
  6141. }
  6142. if (y_non_contig || quantize_y) {
  6143. ctx->prealloc_y_need_sync = true;
  6144. }
  6145. }
  6146. // Device tuning
  6147. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  6148. if (device->mmvq_mode == 1) {
  6149. return true;
  6150. } else if (device->mmvq_mode == -1) {
  6151. return false;
  6152. }
  6153. // General performance issue with q3_k and q6_k due to 2-byte alignment
  6154. if (src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_Q6_K) {
  6155. return false;
  6156. }
  6157. // MMVQ is generally good for batches
  6158. if (n > 1) {
  6159. return true;
  6160. }
  6161. // Quantization overhead is not worth it for small k
  6162. switch (device->vendor_id) {
  6163. case VK_VENDOR_ID_NVIDIA:
  6164. if (src0_type == GGML_TYPE_Q2_K || src0_type == GGML_TYPE_IQ1_S || src0_type == GGML_TYPE_IQ1_M) {
  6165. return true;
  6166. }
  6167. if (k <= 4096) {
  6168. return false;
  6169. }
  6170. switch (src0_type) {
  6171. case GGML_TYPE_MXFP4:
  6172. case GGML_TYPE_Q8_0:
  6173. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  6174. default:
  6175. return true;
  6176. }
  6177. case VK_VENDOR_ID_AMD:
  6178. if (k < 2048) {
  6179. return false;
  6180. }
  6181. switch (src0_type) {
  6182. case GGML_TYPE_Q8_0:
  6183. return device->architecture == vk_device_architecture::AMD_GCN;
  6184. default:
  6185. return true;
  6186. }
  6187. case VK_VENDOR_ID_INTEL:
  6188. if (k < 2048) {
  6189. return false;
  6190. }
  6191. switch (src0_type) {
  6192. // From tests on A770 Linux, may need more tuning
  6193. case GGML_TYPE_Q4_0:
  6194. case GGML_TYPE_Q5_1:
  6195. return false;
  6196. default:
  6197. return true;
  6198. }
  6199. default:
  6200. return true;
  6201. }
  6202. GGML_UNUSED(m);
  6203. }
  6204. 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) {
  6205. ggml_tensor * dst = cgraph->nodes[node_idx];
  6206. const ggml_tensor * src0 = dst->src[0];
  6207. const ggml_tensor * src1 = dst->src[1];
  6208. 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];
  6209. 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];
  6210. 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];
  6211. std::cerr << ")),)");
  6212. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6213. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6214. const uint64_t ne00 = src0->ne[0];
  6215. const uint64_t ne01 = src0->ne[1];
  6216. const uint64_t ne02 = src0->ne[2];
  6217. const uint64_t ne03 = src0->ne[3];
  6218. const uint64_t ne10 = src1->ne[0];
  6219. const uint64_t ne11 = src1->ne[1];
  6220. const uint64_t ne12 = src1->ne[2];
  6221. const uint64_t ne13 = src1->ne[3];
  6222. const uint64_t ne20 = dst->ne[0];
  6223. const uint64_t ne21 = dst->ne[1];
  6224. // const uint64_t ne22 = dst->ne[2];
  6225. // const uint64_t ne23 = dst->ne[3];
  6226. const uint64_t r2 = ne12 / ne02;
  6227. const uint64_t r3 = ne13 / ne03;
  6228. // batch_n indicates that we need to compute a few vector results, and this assumes
  6229. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  6230. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  6231. bool batch_n = ne11 > 1;
  6232. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6233. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6234. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6235. 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);
  6236. vk_pipeline to_fp16_vk_0 = nullptr;
  6237. vk_pipeline to_fp16_vk_1 = nullptr;
  6238. if (x_non_contig) {
  6239. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6240. }
  6241. if (y_non_contig) {
  6242. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6243. } else {
  6244. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6245. }
  6246. // Check for mmq first
  6247. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  6248. vk_pipeline to_q8_1 = nullptr;
  6249. if (dmmv == nullptr) {
  6250. // Fall back to f16 dequant mul mat
  6251. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  6252. quantize_y = false;
  6253. }
  6254. if (quantize_y) {
  6255. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6256. }
  6257. const bool qx_needs_dequant = x_non_contig;
  6258. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6259. // Not implemented
  6260. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6261. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6262. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6263. GGML_ASSERT(dmmv != nullptr);
  6264. const uint64_t x_ne = ggml_nelements(src0);
  6265. const uint64_t y_ne = ggml_nelements(src1);
  6266. 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);
  6267. 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;
  6268. 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)) :
  6269. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6270. {
  6271. if (
  6272. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6273. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6274. GGML_ABORT("Requested preallocation size is too large");
  6275. }
  6276. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6277. ctx->prealloc_size_x = x_sz;
  6278. ggml_vk_preallocate_buffers(ctx, subctx);
  6279. }
  6280. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6281. ctx->prealloc_size_y = y_sz;
  6282. ggml_vk_preallocate_buffers(ctx, subctx);
  6283. }
  6284. // Request descriptor sets
  6285. if (qx_needs_dequant) {
  6286. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6287. }
  6288. if (qy_needs_dequant) {
  6289. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6290. }
  6291. if (quantize_y) {
  6292. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6293. }
  6294. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6295. }
  6296. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6297. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6298. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6299. vk_subbuffer d_X, d_Y;
  6300. if (qx_needs_dequant) {
  6301. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6302. } else {
  6303. d_X = d_Qx;
  6304. GGML_ASSERT(qx_sz == x_sz);
  6305. }
  6306. if (qy_needs_dequant || quantize_y) {
  6307. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6308. } else {
  6309. d_Y = d_Qy;
  6310. }
  6311. if (x_non_contig) {
  6312. if (ctx->prealloc_x_need_sync) {
  6313. ggml_vk_sync_buffers(ctx, subctx);
  6314. }
  6315. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6316. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6317. }
  6318. if (y_non_contig) {
  6319. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6320. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6321. ctx->prealloc_y_last_tensor_used != src1) {
  6322. if (ctx->prealloc_y_need_sync) {
  6323. ggml_vk_sync_buffers(ctx, subctx);
  6324. }
  6325. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6326. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6327. ctx->prealloc_y_last_tensor_used = src1;
  6328. }
  6329. }
  6330. if (quantize_y) {
  6331. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6332. ctx->prealloc_y_last_tensor_used != src1) {
  6333. if (ctx->prealloc_y_need_sync) {
  6334. ggml_vk_sync_buffers(ctx, subctx);
  6335. }
  6336. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6337. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6338. ctx->prealloc_y_last_tensor_used = src1;
  6339. }
  6340. }
  6341. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  6342. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  6343. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  6344. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  6345. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6346. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6347. }
  6348. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6349. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6350. }
  6351. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6352. uint32_t groups_x = ne01;
  6353. uint32_t groups_z = 1;
  6354. if (ne01 > max_groups_x) {
  6355. groups_z = 64;
  6356. groups_x = CEIL_DIV(groups_x, groups_z);
  6357. }
  6358. uint32_t fusion_flags = 0;
  6359. vk_subbuffer d_F0 = d_D;
  6360. if (ctx->num_additional_fused_ops > 0) {
  6361. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6362. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6363. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6364. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6365. }
  6366. vk_subbuffer d_F1 = d_D;
  6367. if (ctx->num_additional_fused_ops == 2) {
  6368. const ggml_tensor * add = cgraph->nodes[node_idx + 2];
  6369. const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0];
  6370. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6371. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6372. }
  6373. // compute
  6374. const vk_mat_vec_push_constants pc = {
  6375. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6376. stride_batch_x, stride_batch_y, stride_batch_d,
  6377. fusion_flags,
  6378. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  6379. };
  6380. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6381. {
  6382. d_X,
  6383. d_Y,
  6384. d_D,
  6385. d_F0,
  6386. d_F1,
  6387. },
  6388. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  6389. if (x_non_contig) {
  6390. ctx->prealloc_x_need_sync = true;
  6391. }
  6392. if (y_non_contig || quantize_y) {
  6393. ctx->prealloc_y_need_sync = true;
  6394. }
  6395. }
  6396. 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) {
  6397. ggml_tensor * dst = cgraph->nodes[node_idx];
  6398. const ggml_tensor * src0 = dst->src[0];
  6399. const ggml_tensor * src1 = dst->src[1];
  6400. 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];
  6401. 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];
  6402. 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];
  6403. std::cerr << "))");
  6404. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  6405. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  6406. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  6407. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6408. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6409. const uint64_t ne00 = src0->ne[0];
  6410. const uint64_t ne01 = src0->ne[1];
  6411. const uint64_t ne02 = src0->ne[2];
  6412. // const uint64_t ne03 = src0->ne[3];
  6413. //const uint64_t ne10 = src1->ne[0];
  6414. const uint64_t ne11 = src1->ne[1];
  6415. const uint64_t ne12 = src1->ne[2];
  6416. // const uint64_t ne13 = src1->ne[3];
  6417. GGML_ASSERT(ne11 == 1);
  6418. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  6419. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  6420. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  6421. gqa_ratio = 1;
  6422. }
  6423. {
  6424. // Request descriptor sets
  6425. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  6426. }
  6427. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6428. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6429. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6430. vk_subbuffer d_F0 = d_D;
  6431. uint32_t fusion_flags = 0;
  6432. if (ctx->num_additional_fused_ops > 0) {
  6433. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6434. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6435. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6436. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6437. }
  6438. vk_subbuffer d_F1 = d_D;
  6439. if (ctx->num_additional_fused_ops > 1) {
  6440. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6441. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6442. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6443. }
  6444. // compute
  6445. vk_mat_vec_p021_push_constants pc = {
  6446. (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12,
  6447. 0, 0, fusion_flags
  6448. };
  6449. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6450. uint32_t workgroups_z = (uint32_t)ne12;
  6451. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  6452. if (gqa_ratio > 1) {
  6453. workgroups_z /= gqa_ratio;
  6454. }
  6455. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6456. {
  6457. d_Qx,
  6458. d_Qy,
  6459. d_D,
  6460. d_F0,
  6461. d_F1,
  6462. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6463. }
  6464. 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) {
  6465. ggml_tensor * dst = cgraph->nodes[node_idx];
  6466. const ggml_tensor * src0 = dst->src[0];
  6467. const ggml_tensor * src1 = dst->src[1];
  6468. 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];
  6469. 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];
  6470. 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];
  6471. std::cerr << "))");
  6472. GGML_ASSERT(!ggml_is_transposed(src0));
  6473. GGML_ASSERT(!ggml_is_transposed(src1));
  6474. GGML_ASSERT(!ggml_is_permuted(src0));
  6475. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6476. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6477. const uint64_t ne00 = src0->ne[0];
  6478. const uint64_t ne01 = src0->ne[1];
  6479. const uint64_t ne02 = src0->ne[2];
  6480. const uint64_t ne03 = src0->ne[3];
  6481. const uint64_t nb01 = src0->nb[1];
  6482. const uint64_t nb02 = src0->nb[2];
  6483. const uint64_t nb12 = src1->nb[2];
  6484. // const uint64_t ne10 = src1->ne[0];
  6485. const uint64_t ne11 = src1->ne[1];
  6486. const uint64_t ne12 = src1->ne[2];
  6487. // const uint64_t ne13 = src1->ne[3];
  6488. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6489. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6490. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6491. GGML_ASSERT(ne11 == 1);
  6492. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6493. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6494. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6495. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6496. {
  6497. // Request descriptor sets
  6498. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6499. }
  6500. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6501. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6502. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6503. vk_subbuffer d_F0 = d_D;
  6504. uint32_t fusion_flags = 0;
  6505. if (ctx->num_additional_fused_ops > 0) {
  6506. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6507. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6508. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6509. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6510. }
  6511. vk_subbuffer d_F1 = d_D;
  6512. if (ctx->num_additional_fused_ops > 1) {
  6513. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6514. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6515. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6516. }
  6517. // compute
  6518. vk_mat_vec_nc_push_constants pc = {
  6519. (uint32_t)ne00, (uint32_t)ne01,
  6520. row_stride_x, channel_stride_x, channel_stride_y,
  6521. (uint32_t)(ne12 / ne02), (uint32_t)ne12,
  6522. 0, 0,
  6523. nb03, nb13, nb23, fusion_flags
  6524. };
  6525. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6526. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6527. {
  6528. d_Qx,
  6529. d_Qy,
  6530. d_D,
  6531. d_F0,
  6532. d_F1,
  6533. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6534. }
  6535. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6536. ggml_tensor * dst = cgraph->nodes[node_idx];
  6537. ggml_tensor * src0 = dst->src[0];
  6538. ggml_tensor * src1 = dst->src[1];
  6539. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6540. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6541. // where the M dimension is very large.
  6542. // Split_k doesn't work with M splitting.
  6543. const size_t nbytes = ggml_nbytes(src0);
  6544. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6545. if (needs_split) {
  6546. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6547. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6548. uint32_t m_offset = 0;
  6549. while (m_offset < dst->ne[0]) {
  6550. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6551. ggml_tensor dst2 = *dst;
  6552. ggml_tensor src02 = *src0;
  6553. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6554. src02.view_src = src0->view_src ? src0->view_src : src0;
  6555. dst2.view_offs += m_offset * dst->nb[0];
  6556. src02.view_offs += m_offset * src0->nb[1];
  6557. dst2.ne[0] = cur_M_size;
  6558. src02.ne[1] = cur_M_size;
  6559. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6560. m_offset += cur_M_size;
  6561. }
  6562. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6563. // detect 0213 permutation, and batch size of 1
  6564. src0->nb[0] <= src0->nb[2] &&
  6565. src0->nb[2] <= src0->nb[1] &&
  6566. src0->nb[1] <= src0->nb[3] &&
  6567. src1->nb[0] <= src1->nb[2] &&
  6568. src1->nb[2] <= src1->nb[1] &&
  6569. src1->nb[1] <= src1->nb[3] &&
  6570. src0->ne[3] == 1 &&
  6571. src1->ne[3] == 1) {
  6572. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6573. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6574. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6575. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6576. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6577. // when ne12 and ne13 are one.
  6578. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6579. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6580. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6581. } else {
  6582. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6583. }
  6584. }
  6585. 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) {
  6586. 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];
  6587. 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];
  6588. 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];
  6589. 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] << "),)");
  6590. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6591. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6592. const uint64_t ne00 = src0->ne[0];
  6593. const uint64_t ne01 = src0->ne[1];
  6594. const uint64_t ne02 = src0->ne[2];
  6595. // const uint64_t ne03 = src0->ne[3];
  6596. const uint64_t ne10 = src1->ne[0];
  6597. const uint64_t ne11 = src1->ne[1];
  6598. const uint64_t ne12 = src1->ne[2];
  6599. const uint64_t ne13 = src1->ne[3];
  6600. const uint64_t nei0 = ids->ne[0];
  6601. const uint64_t nei1 = ids->ne[1];
  6602. const uint32_t nbi0 = ids->nb[0];
  6603. const uint32_t nbi1 = ids->nb[1];
  6604. const uint32_t nbi2 = ids->nb[2];
  6605. const uint64_t ne20 = dst->ne[0];
  6606. const uint64_t ne21 = dst->ne[1];
  6607. // const uint64_t ne22 = dst->ne[2];
  6608. // const uint64_t ne23 = dst->ne[3];
  6609. const uint64_t n_as = ne02;
  6610. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6611. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6612. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6613. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6614. vk_buffer d_Qx = nullptr;
  6615. size_t qx_buf_offset = 0;
  6616. vk_buffer d_Qy = nullptr;
  6617. size_t qy_buf_offset = 0;
  6618. vk_buffer d_ids = nullptr;
  6619. size_t ids_buf_offset = 0;
  6620. bool src0_uma = false;
  6621. bool src1_uma = false;
  6622. bool ids_uma = false;
  6623. if (ctx->device->uma) {
  6624. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6625. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6626. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6627. src0_uma = d_Qx != nullptr;
  6628. src1_uma = d_Qy != nullptr;
  6629. ids_uma = d_ids != nullptr;
  6630. }
  6631. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6632. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6633. !ggml_vk_dim01_contiguous(src0);
  6634. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6635. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6636. !ggml_vk_dim01_contiguous(src1);
  6637. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6638. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6639. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6640. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6641. // Check for mmq first
  6642. 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;
  6643. if (mmp == nullptr) {
  6644. // Fall back to f16 dequant mul mat
  6645. 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]);
  6646. quantize_y = false;
  6647. }
  6648. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6649. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6650. if (qx_needs_dequant) {
  6651. // Fall back to dequant + f16 mulmat
  6652. 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]);
  6653. }
  6654. // Not implemented
  6655. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6656. 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));
  6657. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6658. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6659. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6660. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6661. const uint64_t x_ne = ggml_nelements(src0);
  6662. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6663. const uint64_t d_ne = ggml_nelements(dst);
  6664. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6665. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6666. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6667. 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);
  6668. const uint64_t ids_sz = nbi2;
  6669. const uint64_t d_sz = sizeof(float) * d_ne;
  6670. vk_pipeline to_fp16_vk_0 = nullptr;
  6671. vk_pipeline to_fp16_vk_1 = nullptr;
  6672. vk_pipeline to_q8_1 = nullptr;
  6673. if (x_non_contig) {
  6674. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6675. } else {
  6676. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6677. }
  6678. if (y_non_contig) {
  6679. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6680. } else {
  6681. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6682. }
  6683. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6684. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6685. if (quantize_y) {
  6686. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6687. }
  6688. vk_pipeline count_experts = ctx->device->pipeline_count_experts;
  6689. uint32_t expert_count_size = sizeof(uint32_t) * n_as;
  6690. {
  6691. if (
  6692. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6693. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6694. GGML_ABORT("Requested preallocation size is too large");
  6695. }
  6696. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6697. ctx->prealloc_size_x = x_sz;
  6698. ggml_vk_preallocate_buffers(ctx, subctx);
  6699. }
  6700. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6701. ctx->prealloc_size_y = y_sz;
  6702. ggml_vk_preallocate_buffers(ctx, subctx);
  6703. }
  6704. if (ctx->prealloc_size_split_k < expert_count_size) {
  6705. ctx->prealloc_size_split_k = expert_count_size;
  6706. ggml_vk_preallocate_buffers(ctx, subctx);
  6707. }
  6708. // Request descriptor sets
  6709. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6710. if (qx_needs_dequant) {
  6711. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6712. }
  6713. if (qy_needs_dequant) {
  6714. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6715. }
  6716. if (quantize_y) {
  6717. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6718. }
  6719. ggml_pipeline_request_descriptor_sets(ctx, count_experts, 1);
  6720. }
  6721. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6722. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6723. GGML_ASSERT(d_D != nullptr);
  6724. vk_buffer d_X;
  6725. uint64_t x_buf_offset = 0;
  6726. vk_buffer d_Y;
  6727. uint64_t y_buf_offset = 0;
  6728. if (!src0_uma) {
  6729. d_Qx = src0_buf_ctx->dev_buffer;
  6730. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6731. GGML_ASSERT(d_Qx != nullptr);
  6732. }
  6733. if (!src1_uma) {
  6734. d_Qy = src1_buf_ctx->dev_buffer;
  6735. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6736. GGML_ASSERT(d_Qy != nullptr);
  6737. }
  6738. if (!ids_uma) {
  6739. d_ids = ids_buf_ctx->dev_buffer;
  6740. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6741. GGML_ASSERT(d_ids != nullptr);
  6742. }
  6743. if (qx_needs_dequant) {
  6744. d_X = ctx->prealloc_x;
  6745. GGML_ASSERT(d_X->size >= x_sz);
  6746. } else {
  6747. d_X = d_Qx;
  6748. x_buf_offset = qx_buf_offset;
  6749. GGML_ASSERT(qx_sz == x_sz);
  6750. }
  6751. if (qy_needs_dequant) {
  6752. d_Y = ctx->prealloc_y;
  6753. GGML_ASSERT(d_Y->size >= y_sz);
  6754. } else if (quantize_y) {
  6755. d_Y = ctx->prealloc_y;
  6756. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6757. } else {
  6758. d_Y = d_Qy;
  6759. y_buf_offset = qy_buf_offset;
  6760. GGML_ASSERT(qy_sz == y_sz);
  6761. }
  6762. if (x_non_contig || qx_needs_dequant) {
  6763. if (ctx->prealloc_x_need_sync) {
  6764. ggml_vk_sync_buffers(ctx, subctx);
  6765. }
  6766. }
  6767. // Count how many times each expert is used
  6768. vk_subbuffer expert_count_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  6769. if (ctx->prealloc_split_k_need_sync) {
  6770. ggml_vk_sync_buffers(ctx, subctx);
  6771. }
  6772. {
  6773. const std::vector<uint32_t> pc = { (uint32_t)nei0,
  6774. (uint32_t)nei1,
  6775. (uint32_t)(nbi0 / ggml_type_size(ids->type)),
  6776. (uint32_t)(nbi1 / ggml_type_size(ids->type)),
  6777. (uint32_t)(get_misalign_bytes(ctx, ids) / ggml_type_size(ids->type)) };
  6778. ggml_vk_dispatch_pipeline(ctx, subctx, count_experts,
  6779. { vk_subbuffer{ d_ids, ids_buf_offset, ids_sz }, expert_count_buf }, pc, { (uint32_t)n_as, 1, 1});
  6780. }
  6781. if (x_non_contig) {
  6782. 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));
  6783. } else if (qx_needs_dequant) {
  6784. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6785. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6786. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6787. }
  6788. if (y_non_contig) {
  6789. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6790. ctx->prealloc_y_last_tensor_used != src1) {
  6791. if (ctx->prealloc_y_need_sync) {
  6792. ggml_vk_sync_buffers(ctx, subctx);
  6793. }
  6794. 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));
  6795. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6796. ctx->prealloc_y_last_tensor_used = src1;
  6797. }
  6798. }
  6799. if (quantize_y) {
  6800. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6801. ctx->prealloc_y_last_tensor_used != src1) {
  6802. if (ctx->prealloc_y_need_sync) {
  6803. ggml_vk_sync_buffers(ctx, subctx);
  6804. }
  6805. 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);
  6806. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6807. ctx->prealloc_y_last_tensor_used = src1;
  6808. }
  6809. }
  6810. ggml_vk_sync_buffers(ctx, subctx);
  6811. uint32_t stride_batch_x = ne00*ne01;
  6812. uint32_t stride_batch_y = ne10*ne11;
  6813. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6814. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6815. }
  6816. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6817. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6818. }
  6819. // compute
  6820. ggml_vk_matmul_id(
  6821. ctx, subctx, pipeline,
  6822. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6823. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz }, expert_count_buf,
  6824. ne01, ne21, ne10, ne10, ne10, ne01,
  6825. stride_batch_x, stride_batch_y, ne20*ne21,
  6826. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6827. ); // NOLINT
  6828. if (x_non_contig || qx_needs_dequant) {
  6829. ctx->prealloc_x_need_sync = true;
  6830. }
  6831. if (y_non_contig || quantize_y) {
  6832. ctx->prealloc_y_need_sync = true;
  6833. }
  6834. ctx->prealloc_split_k_need_sync = true;
  6835. }
  6836. 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) {
  6837. ggml_tensor * dst = cgraph->nodes[node_idx];
  6838. ggml_tensor * src0 = dst->src[0];
  6839. ggml_tensor * src1 = dst->src[1];
  6840. ggml_tensor * ids = dst->src[2];
  6841. 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];
  6842. 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];
  6843. 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];
  6844. 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];
  6845. std::cerr << "))");
  6846. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6847. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6848. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6849. const uint64_t ne00 = src0->ne[0];
  6850. const uint64_t ne01 = src0->ne[1];
  6851. // const uint64_t ne02 = src0->ne[2];
  6852. // const uint64_t ne03 = src0->ne[3];
  6853. const uint64_t ne10 = src1->ne[0];
  6854. const uint64_t ne11 = src1->ne[1];
  6855. const uint64_t ne12 = src1->ne[2];
  6856. // const uint64_t ne13 = src1->ne[3];
  6857. const uint64_t nei0 = ids->ne[0];
  6858. const uint64_t nei1 = ids->ne[1];
  6859. GGML_ASSERT(nei1 == 1);
  6860. const uint64_t ne20 = dst->ne[0];
  6861. const uint64_t ne21 = dst->ne[1];
  6862. // const uint64_t ne22 = dst->ne[2];
  6863. // const uint64_t ne23 = dst->ne[3];
  6864. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6865. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6866. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6867. 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);
  6868. vk_pipeline to_fp16_vk_0 = nullptr;
  6869. vk_pipeline to_fp16_vk_1 = nullptr;
  6870. if (x_non_contig) {
  6871. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6872. }
  6873. if (y_non_contig) {
  6874. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6875. } else {
  6876. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6877. }
  6878. // Check for mmq first
  6879. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00) : nullptr;
  6880. vk_pipeline to_q8_1 = nullptr;
  6881. if (dmmv == nullptr) {
  6882. // Fall back to f16 dequant mul mat
  6883. dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00);
  6884. quantize_y = false;
  6885. }
  6886. if (quantize_y) {
  6887. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6888. }
  6889. const bool qx_needs_dequant = x_non_contig;
  6890. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6891. // Not implemented
  6892. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6893. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6894. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6895. GGML_ASSERT(dmmv != nullptr);
  6896. const uint64_t x_ne = ggml_nelements(src0);
  6897. const uint64_t y_ne = ggml_nelements(src1);
  6898. 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);
  6899. 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;
  6900. 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)) :
  6901. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6902. {
  6903. if (
  6904. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6905. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6906. GGML_ABORT("Requested preallocation size is too large");
  6907. }
  6908. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6909. ctx->prealloc_size_x = x_sz;
  6910. ggml_vk_preallocate_buffers(ctx, subctx);
  6911. }
  6912. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6913. ctx->prealloc_size_y = y_sz;
  6914. ggml_vk_preallocate_buffers(ctx, subctx);
  6915. }
  6916. // Request descriptor sets
  6917. if (qx_needs_dequant) {
  6918. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6919. }
  6920. if (qy_needs_dequant) {
  6921. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6922. }
  6923. if (quantize_y) {
  6924. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6925. }
  6926. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6927. }
  6928. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6929. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6930. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6931. vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids);
  6932. vk_subbuffer d_F0 = d_D;
  6933. vk_subbuffer d_X, d_Y;
  6934. if (qx_needs_dequant) {
  6935. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6936. } else {
  6937. d_X = d_Qx;
  6938. }
  6939. if (qy_needs_dequant || quantize_y) {
  6940. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6941. } else {
  6942. d_Y = d_Qy;
  6943. }
  6944. if (x_non_contig) {
  6945. if (ctx->prealloc_x_need_sync) {
  6946. ggml_vk_sync_buffers(ctx, subctx);
  6947. }
  6948. }
  6949. if (x_non_contig) {
  6950. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6951. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6952. }
  6953. if (y_non_contig) {
  6954. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6955. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6956. ctx->prealloc_y_last_tensor_used != src1) {
  6957. if (ctx->prealloc_y_need_sync) {
  6958. ggml_vk_sync_buffers(ctx, subctx);
  6959. }
  6960. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6961. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6962. ctx->prealloc_y_last_tensor_used = src1;
  6963. }
  6964. }
  6965. if (quantize_y) {
  6966. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6967. ctx->prealloc_y_last_tensor_used != src1) {
  6968. if (ctx->prealloc_y_need_sync) {
  6969. ggml_vk_sync_buffers(ctx, subctx);
  6970. }
  6971. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6972. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6973. ctx->prealloc_y_last_tensor_used = src1;
  6974. }
  6975. }
  6976. uint32_t stride_batch_y = ne10*ne11;
  6977. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6978. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6979. }
  6980. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6981. uint32_t groups_x = ne01;
  6982. uint32_t groups_z = 1;
  6983. if (ne01 > max_groups_x) {
  6984. groups_z = 64;
  6985. groups_x = CEIL_DIV(groups_x, groups_z);
  6986. }
  6987. uint32_t fusion_flags = 0;
  6988. if (ctx->num_additional_fused_ops > 0) {
  6989. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6990. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6991. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  6992. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0;
  6993. } else {
  6994. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  6995. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6996. }
  6997. }
  6998. vk_subbuffer d_F1 = d_D;
  6999. if (ctx->num_additional_fused_ops > 1) {
  7000. const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1];
  7001. d_F1 = ggml_vk_tensor_subbuffer(ctx, scale);
  7002. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
  7003. }
  7004. // compute
  7005. const vk_mat_vec_id_push_constants pc = {
  7006. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  7007. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  7008. fusion_flags,
  7009. (uint32_t)nei0, (uint32_t)ne11,
  7010. };
  7011. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  7012. {
  7013. d_X,
  7014. d_Y,
  7015. d_D,
  7016. d_F0,
  7017. d_F1,
  7018. d_ids,
  7019. },
  7020. pc, { groups_x, (uint32_t)nei0, groups_z });
  7021. if (x_non_contig) {
  7022. ctx->prealloc_x_need_sync = true;
  7023. }
  7024. if (y_non_contig || quantize_y) {
  7025. ctx->prealloc_y_need_sync = true;
  7026. }
  7027. }
  7028. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  7029. ggml_tensor * dst = cgraph->nodes[node_idx];
  7030. ggml_tensor * src0 = dst->src[0];
  7031. ggml_tensor * src2 = dst->src[2];
  7032. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  7033. }
  7034. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  7035. ggml_tensor * dst = cgraph->nodes[node_idx];
  7036. ggml_tensor * src0 = dst->src[0];
  7037. ggml_tensor * src1 = dst->src[1];
  7038. ggml_tensor * src2 = dst->src[2];
  7039. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  7040. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  7041. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  7042. } else {
  7043. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  7044. }
  7045. }
  7046. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool small_cache) {
  7047. // Needs to be kept up to date on shader changes
  7048. GGML_UNUSED(hsv);
  7049. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  7050. const uint32_t Br = get_fa_scalar_num_large_rows(hsk, hsv, small_cache);
  7051. const uint32_t Bc = scalar_flash_attention_Bc;
  7052. const uint32_t tmpsh = wg_size * sizeof(float);
  7053. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  7054. const uint32_t masksh = Bc * Br * sizeof(float);
  7055. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  7056. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  7057. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  7058. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  7059. return supported;
  7060. }
  7061. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  7062. // Needs to be kept up to date on shader changes
  7063. GGML_UNUSED(hsv);
  7064. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  7065. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  7066. const uint32_t Bc = scalar_flash_attention_Bc;
  7067. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  7068. const uint32_t acctype = f32acc ? 4 : 2;
  7069. const uint32_t f16vec4 = 8;
  7070. const uint32_t tmpsh = wg_size * sizeof(float);
  7071. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  7072. const uint32_t qstride = hsk_pad / 4 + 2;
  7073. const uint32_t Qf = Br * qstride * f16vec4;
  7074. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  7075. const uint32_t sfsh = Bc * sfshstride * acctype;
  7076. const uint32_t kshstride = hsk_pad / 4 + 2;
  7077. const uint32_t ksh = Bc * kshstride * f16vec4;
  7078. const uint32_t slope = Br * sizeof(float);
  7079. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  7080. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  7081. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  7082. return supported;
  7083. }
  7084. 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) {
  7085. 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];
  7086. 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];
  7087. 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];
  7088. 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];
  7089. if (sinks) {
  7090. 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];
  7091. }
  7092. std::cerr << "))");
  7093. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  7094. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  7095. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  7096. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  7097. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  7098. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  7099. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  7100. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  7101. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  7102. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  7103. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  7104. const uint32_t HSK = nek0;
  7105. const uint32_t HSV = nev0;
  7106. uint32_t N = neq1;
  7107. const uint32_t KV = nek1;
  7108. GGML_ASSERT(ne0 == HSV);
  7109. GGML_ASSERT(ne2 == N);
  7110. // input tensor rows must be contiguous
  7111. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  7112. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  7113. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  7114. GGML_ASSERT(neq0 == HSK);
  7115. GGML_ASSERT(neq1 == N);
  7116. GGML_ASSERT(nev1 == nek1);
  7117. // dst cannot be transposed or permuted
  7118. GGML_ASSERT(nb0 == sizeof(float));
  7119. GGML_ASSERT(nb0 <= nb1);
  7120. GGML_ASSERT(nb1 <= nb2);
  7121. GGML_ASSERT(nb2 <= nb3);
  7122. assert(dst->type == GGML_TYPE_F32);
  7123. assert(q->type == GGML_TYPE_F32);
  7124. assert(k->type == v->type);
  7125. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  7126. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  7127. if (path == FA_COOPMAT1) {
  7128. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  7129. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  7130. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  7131. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  7132. path = FA_SCALAR;
  7133. }
  7134. }
  7135. uint32_t gqa_ratio = 1;
  7136. uint32_t qk_ratio = neq2 / nek2;
  7137. uint32_t workgroups_x = (uint32_t)neq1;
  7138. uint32_t workgroups_y = (uint32_t)neq2;
  7139. uint32_t workgroups_z = (uint32_t)neq3;
  7140. const bool small_cache = nek1 < 1024;
  7141. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  7142. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  7143. uint32_t max_gqa;
  7144. switch (path) {
  7145. case FA_SCALAR:
  7146. case FA_COOPMAT1:
  7147. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  7148. max_gqa = get_fa_scalar_num_large_rows(HSK, HSV, small_cache);
  7149. break;
  7150. case FA_COOPMAT2:
  7151. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  7152. break;
  7153. default:
  7154. GGML_ASSERT(0);
  7155. }
  7156. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  7157. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  7158. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  7159. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  7160. // and change addressing calculations to index Q's dimension 2.
  7161. gqa_ratio = qk_ratio;
  7162. N = gqa_ratio;
  7163. workgroups_y /= N;
  7164. }
  7165. bool small_rows = N <= get_fa_num_small_rows(path);
  7166. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  7167. // So use scalar instead.
  7168. if (small_rows && path == FA_COOPMAT1) {
  7169. path = FA_SCALAR;
  7170. }
  7171. // scalar is faster than coopmat2 when N==1
  7172. if (N == 1 && path == FA_COOPMAT2) {
  7173. path = FA_SCALAR;
  7174. }
  7175. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  7176. if (path == FA_SCALAR &&
  7177. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV, small_cache)) {
  7178. small_rows = true;
  7179. }
  7180. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  7181. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  7182. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  7183. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  7184. if (k->type == GGML_TYPE_F32) {
  7185. k_stride /= 4;
  7186. }
  7187. if (v->type == GGML_TYPE_F32) {
  7188. v_stride /= 4;
  7189. }
  7190. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows, small_cache);
  7191. bool aligned = (KV % alignment) == 0 &&
  7192. // the "aligned" shader variant will forcibly align strides, for performance
  7193. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  7194. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  7195. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  7196. aligned = false;
  7197. }
  7198. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  7199. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, small_cache, path, aligned, f32acc);
  7200. vk_pipeline pipeline = nullptr;
  7201. {
  7202. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7203. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  7204. auto it = pipelines.find(fa_pipeline_state);
  7205. if (it != pipelines.end()) {
  7206. pipeline = it->second;
  7207. } else {
  7208. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7209. }
  7210. }
  7211. assert(pipeline);
  7212. uint32_t split_kv = KV;
  7213. uint32_t split_k = 1;
  7214. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  7215. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  7216. // Try to use split_k when KV is large enough to be worth the overhead
  7217. if (workgroups_x == 1 && shader_core_count > 0) {
  7218. // Try to run two workgroups per SM.
  7219. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  7220. if (split_k > 1) {
  7221. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  7222. // of "align", so recompute split_k based on that.
  7223. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  7224. split_k = CEIL_DIV(KV, split_kv);
  7225. workgroups_x = split_k;
  7226. }
  7227. }
  7228. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  7229. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  7230. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  7231. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  7232. GGML_ABORT("Requested preallocation size is too large");
  7233. }
  7234. if (ctx->prealloc_size_split_k < split_k_size) {
  7235. ctx->prealloc_size_split_k = split_k_size;
  7236. ggml_vk_preallocate_buffers(ctx, subctx);
  7237. }
  7238. {
  7239. // Request descriptor sets
  7240. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7241. if (split_k > 1) {
  7242. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  7243. }
  7244. }
  7245. float scale = 1.0f;
  7246. float max_bias = 0.0f;
  7247. float logit_softcap = 0.0f;
  7248. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  7249. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  7250. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  7251. if (logit_softcap != 0) {
  7252. scale /= logit_softcap;
  7253. }
  7254. const uint32_t n_head_kv = neq2;
  7255. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  7256. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  7257. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  7258. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  7259. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  7260. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  7261. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  7262. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  7263. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  7264. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  7265. const vk_flash_attn_push_constants pc = { N, KV,
  7266. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  7267. (uint32_t)neq2, (uint32_t)neq3,
  7268. (uint32_t)nek2, (uint32_t)nek3,
  7269. (uint32_t)nev2, (uint32_t)nev3,
  7270. nem1, nem2, nem3,
  7271. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  7272. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  7273. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  7274. scale, max_bias, logit_softcap,
  7275. mask_n_head_log2, m0, m1,
  7276. gqa_ratio, split_kv, split_k };
  7277. if (split_k > 1) {
  7278. if (ctx->prealloc_split_k_need_sync) {
  7279. ggml_vk_sync_buffers(ctx, subctx);
  7280. }
  7281. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  7282. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7283. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  7284. // We only use split_k when group query attention is enabled, which means
  7285. // there's no more than one tile of rows (i.e. workgroups_x would have been
  7286. // one). We reuse workgroups_x to mean the number of splits, so we need to
  7287. // cancel out the divide by wg_denoms[0].
  7288. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  7289. ggml_vk_sync_buffers(ctx, subctx);
  7290. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  7291. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  7292. {split_k_buf, sinks_buf, dst_buf},
  7293. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  7294. ctx->prealloc_split_k_need_sync = true;
  7295. } else {
  7296. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7297. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  7298. pc, { workgroups_x, workgroups_y, workgroups_z });
  7299. }
  7300. }
  7301. static vk_conv_shapes ggml_vk_conv_select_shape(ggml_backend_vk_context * ctx, uint32_t K, uint32_t NPQ) {
  7302. auto n_tiles = [&](vk_conv_shapes s) {
  7303. return CEIL_DIV(K, vk_conv_block_sizes[s].K)
  7304. * CEIL_DIV(NPQ, vk_conv_block_sizes[s].NPQ);
  7305. };
  7306. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7307. // so small convolutions will still choose a smaller tile.
  7308. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7309. if (K > 64 && n_tiles(CONV_SHAPE_128x128) >= shader_core_count * 2) {
  7310. return CONV_SHAPE_128x128;
  7311. } else if (K <= 32 && n_tiles(CONV_SHAPE_32x256) >= shader_core_count * 2) {
  7312. return CONV_SHAPE_32x256;
  7313. } else {
  7314. return CONV_SHAPE_64x32;
  7315. }
  7316. }
  7317. 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) {
  7318. switch (op) {
  7319. case GGML_OP_GET_ROWS:
  7320. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  7321. if (src0->type == GGML_TYPE_I32) {
  7322. // i32 src only supports i32 result
  7323. GGML_ASSERT(dst->type == GGML_TYPE_I32);
  7324. return ctx->device->pipeline_get_rows[src0->type];
  7325. }
  7326. if (dst->type == GGML_TYPE_F16) {
  7327. return ctx->device->pipeline_get_rows[src0->type];
  7328. }
  7329. if (dst->type == GGML_TYPE_F32) {
  7330. return ctx->device->pipeline_get_rows_f32[src0->type];
  7331. }
  7332. return nullptr;
  7333. case GGML_OP_ACC:
  7334. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7335. return ctx->device->pipeline_acc_f32;
  7336. }
  7337. return nullptr;
  7338. case GGML_OP_ADD:
  7339. case GGML_OP_SUB:
  7340. case GGML_OP_MUL:
  7341. case GGML_OP_DIV:
  7342. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7343. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  7344. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  7345. return nullptr;
  7346. }
  7347. switch (op) {
  7348. case GGML_OP_ADD:
  7349. {
  7350. if (ctx->num_additional_fused_ops > 0) {
  7351. if (ctx->do_add_rms_partials) {
  7352. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  7353. } else {
  7354. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  7355. }
  7356. }
  7357. if (ctx->do_add_rms_partials) {
  7358. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  7359. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7360. } else {
  7361. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  7362. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7363. }
  7364. }
  7365. case GGML_OP_SUB:
  7366. {
  7367. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  7368. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7369. }
  7370. case GGML_OP_MUL:
  7371. {
  7372. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  7373. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7374. }
  7375. case GGML_OP_DIV:
  7376. {
  7377. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  7378. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7379. }
  7380. default:
  7381. break;
  7382. }
  7383. return nullptr;
  7384. case GGML_OP_ADD_ID:
  7385. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7386. return ctx->device->pipeline_add_id_f32;
  7387. }
  7388. return nullptr;
  7389. case GGML_OP_CONCAT:
  7390. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7391. return ctx->device->pipeline_concat_f32;
  7392. }
  7393. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7394. return ctx->device->pipeline_concat_f16;
  7395. }
  7396. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7397. return ctx->device->pipeline_concat_i32;
  7398. }
  7399. return nullptr;
  7400. case GGML_OP_UPSCALE:
  7401. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7402. uint32_t mode = (ggml_get_op_params_i32(dst, 0) & (0xFF | GGML_SCALE_FLAG_ANTIALIAS));
  7403. switch (mode) {
  7404. case GGML_SCALE_MODE_NEAREST:
  7405. return ctx->device->pipeline_upscale_nearest_f32;
  7406. case GGML_SCALE_MODE_BILINEAR:
  7407. return ctx->device->pipeline_upscale_bilinear_f32;
  7408. case GGML_SCALE_MODE_BICUBIC:
  7409. return ctx->device->pipeline_upscale_bicubic_f32;
  7410. case GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS:
  7411. return ctx->device->pipeline_upscale_bilinear_antialias_f32;
  7412. default:
  7413. return nullptr;
  7414. }
  7415. }
  7416. return nullptr;
  7417. case GGML_OP_SCALE:
  7418. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7419. return ctx->device->pipeline_scale_f32;
  7420. }
  7421. return nullptr;
  7422. case GGML_OP_SQR:
  7423. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7424. return ctx->device->pipeline_sqr_f32;
  7425. }
  7426. return nullptr;
  7427. case GGML_OP_SQRT:
  7428. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7429. return ctx->device->pipeline_sqrt_f32;
  7430. }
  7431. return nullptr;
  7432. case GGML_OP_SIN:
  7433. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7434. return ctx->device->pipeline_sin_f32;
  7435. }
  7436. return nullptr;
  7437. case GGML_OP_COS:
  7438. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7439. return ctx->device->pipeline_cos_f32;
  7440. }
  7441. return nullptr;
  7442. case GGML_OP_LOG:
  7443. if (src0->type == dst->type &&
  7444. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7445. return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16];
  7446. }
  7447. return nullptr;
  7448. case GGML_OP_TRI:
  7449. if (src0->type == dst->type &&
  7450. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7451. return ctx->device->pipeline_tri[dst->type == GGML_TYPE_F16];
  7452. }
  7453. return nullptr;
  7454. case GGML_OP_DIAG:
  7455. if (src0->type == dst->type &&
  7456. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7457. return ctx->device->pipeline_diag[dst->type == GGML_TYPE_F16];
  7458. }
  7459. return nullptr;
  7460. case GGML_OP_CLAMP:
  7461. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7462. return ctx->device->pipeline_clamp_f32;
  7463. }
  7464. return nullptr;
  7465. case GGML_OP_PAD:
  7466. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7467. return ctx->device->pipeline_pad_f32;
  7468. }
  7469. return nullptr;
  7470. case GGML_OP_ROLL:
  7471. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7472. return ctx->device->pipeline_roll_f32;
  7473. }
  7474. return nullptr;
  7475. case GGML_OP_REPEAT:
  7476. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7477. return ctx->device->pipeline_repeat_f32;
  7478. }
  7479. return nullptr;
  7480. case GGML_OP_REPEAT_BACK:
  7481. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7482. return ctx->device->pipeline_repeat_back_f32;
  7483. }
  7484. return nullptr;
  7485. case GGML_OP_CPY:
  7486. case GGML_OP_CONT:
  7487. case GGML_OP_DUP:
  7488. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7489. case GGML_OP_SET_ROWS:
  7490. if (src1->type == GGML_TYPE_I64) {
  7491. return ctx->device->pipeline_set_rows_i64[dst->type];
  7492. } else {
  7493. return ctx->device->pipeline_set_rows_i32[dst->type];
  7494. }
  7495. case GGML_OP_SILU_BACK:
  7496. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7497. return ctx->device->pipeline_silu_back_f32;
  7498. }
  7499. return nullptr;
  7500. case GGML_OP_NORM:
  7501. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7502. return ctx->device->pipeline_norm_f32;
  7503. }
  7504. return nullptr;
  7505. case GGML_OP_GROUP_NORM:
  7506. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7507. return ctx->device->pipeline_group_norm_f32;
  7508. }
  7509. return nullptr;
  7510. case GGML_OP_RMS_NORM:
  7511. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7512. if (ctx->do_add_rms_partials) {
  7513. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7514. } else {
  7515. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7516. }
  7517. }
  7518. return nullptr;
  7519. case GGML_OP_RMS_NORM_BACK:
  7520. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7521. return ctx->device->pipeline_rms_norm_back_f32;
  7522. }
  7523. return nullptr;
  7524. case GGML_OP_L2_NORM:
  7525. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7526. return ctx->device->pipeline_l2_norm_f32;
  7527. }
  7528. return nullptr;
  7529. case GGML_OP_UNARY:
  7530. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7531. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7532. (src0->type != dst->type)) {
  7533. return nullptr;
  7534. }
  7535. switch (ggml_get_unary_op(dst)) {
  7536. case GGML_UNARY_OP_EXP:
  7537. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7538. case GGML_UNARY_OP_SILU:
  7539. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7540. case GGML_UNARY_OP_GELU:
  7541. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7542. case GGML_UNARY_OP_GELU_ERF:
  7543. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7544. case GGML_UNARY_OP_GELU_QUICK:
  7545. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7546. case GGML_UNARY_OP_RELU:
  7547. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7548. case GGML_UNARY_OP_XIELU:
  7549. return ctx->device->pipeline_xielu[dst->type == GGML_TYPE_F16];
  7550. case GGML_UNARY_OP_NEG:
  7551. return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16];
  7552. case GGML_UNARY_OP_TANH:
  7553. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7554. case GGML_UNARY_OP_SIGMOID:
  7555. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7556. case GGML_UNARY_OP_HARDSIGMOID:
  7557. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7558. case GGML_UNARY_OP_HARDSWISH:
  7559. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7560. case GGML_UNARY_OP_ABS:
  7561. return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16];
  7562. case GGML_UNARY_OP_SOFTPLUS:
  7563. return ctx->device->pipeline_softplus[dst->type == GGML_TYPE_F16];
  7564. case GGML_UNARY_OP_STEP:
  7565. return ctx->device->pipeline_step[dst->type == GGML_TYPE_F16];
  7566. case GGML_UNARY_OP_ROUND:
  7567. return ctx->device->pipeline_round[dst->type == GGML_TYPE_F16];
  7568. case GGML_UNARY_OP_CEIL:
  7569. return ctx->device->pipeline_ceil[dst->type == GGML_TYPE_F16];
  7570. case GGML_UNARY_OP_FLOOR:
  7571. return ctx->device->pipeline_floor[dst->type == GGML_TYPE_F16];
  7572. case GGML_UNARY_OP_TRUNC:
  7573. return ctx->device->pipeline_trunc[dst->type == GGML_TYPE_F16];
  7574. default:
  7575. break;
  7576. }
  7577. return nullptr;
  7578. case GGML_OP_GLU:
  7579. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7580. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7581. (src0->type != dst->type)) {
  7582. return nullptr;
  7583. }
  7584. switch (ggml_get_glu_op(dst)) {
  7585. case GGML_GLU_OP_GEGLU:
  7586. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7587. case GGML_GLU_OP_REGLU:
  7588. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7589. case GGML_GLU_OP_SWIGLU:
  7590. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7591. case GGML_GLU_OP_SWIGLU_OAI:
  7592. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7593. case GGML_GLU_OP_GEGLU_ERF:
  7594. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7595. case GGML_GLU_OP_GEGLU_QUICK:
  7596. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7597. default:
  7598. break;
  7599. }
  7600. return nullptr;
  7601. case GGML_OP_DIAG_MASK_INF:
  7602. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7603. return ctx->device->pipeline_diag_mask_inf_f32;
  7604. }
  7605. return nullptr;
  7606. case GGML_OP_SOFT_MAX:
  7607. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7608. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7609. if (ctx->num_additional_fused_ops) {
  7610. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7611. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7612. // use n_experts from push constant if it's not equal to the power of two spec constant
  7613. bool use_push = dst->ne[0] != (1u << idx);
  7614. return ctx->device->pipeline_topk_moe[idx][use_push];
  7615. }
  7616. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7617. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7618. }
  7619. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7620. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7621. }
  7622. return nullptr;
  7623. case GGML_OP_SOFT_MAX_BACK:
  7624. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7625. return ctx->device->pipeline_soft_max_back_f32;
  7626. }
  7627. return nullptr;
  7628. case GGML_OP_ROPE:
  7629. case GGML_OP_ROPE_BACK:
  7630. {
  7631. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7632. const int mode = ((const int32_t *) rope->op_params)[2];
  7633. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7634. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7635. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7636. if (is_neox) {
  7637. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7638. return ctx->device->pipeline_rope_neox_f32;
  7639. }
  7640. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7641. return ctx->device->pipeline_rope_neox_f32_f16;
  7642. }
  7643. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7644. return ctx->device->pipeline_rope_neox_f16;
  7645. }
  7646. } else if (is_mrope && !is_vision) {
  7647. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7648. return ctx->device->pipeline_rope_multi_f32;
  7649. }
  7650. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7651. return ctx->device->pipeline_rope_multi_f32_f16;
  7652. }
  7653. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7654. return ctx->device->pipeline_rope_multi_f16;
  7655. }
  7656. } else if (is_vision) {
  7657. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7658. return ctx->device->pipeline_rope_vision_f32;
  7659. }
  7660. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7661. return ctx->device->pipeline_rope_vision_f16;
  7662. }
  7663. } else {
  7664. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7665. return ctx->device->pipeline_rope_norm_f32;
  7666. }
  7667. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7668. return ctx->device->pipeline_rope_norm_f32_f16;
  7669. }
  7670. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7671. return ctx->device->pipeline_rope_norm_f16;
  7672. }
  7673. }
  7674. return nullptr;
  7675. }
  7676. case GGML_OP_SUM:
  7677. case GGML_OP_SUM_ROWS:
  7678. case GGML_OP_MEAN:
  7679. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7680. return ctx->device->pipeline_sum_rows_f32;
  7681. }
  7682. return nullptr;
  7683. case GGML_OP_CUMSUM:
  7684. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7685. if (src0->ne[0] <= 512) {
  7686. return ctx->device->pipeline_cumsum_small_f32;
  7687. } else {
  7688. return ctx->device->pipeline_cumsum_f32;
  7689. }
  7690. }
  7691. return nullptr;
  7692. case GGML_OP_SOLVE_TRI:
  7693. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7694. vk_solve_tri_pipeline_state solve_tri_pipeline_state(src0->ne[0], src1->ne[0]);
  7695. vk_pipeline pipeline = nullptr;
  7696. {
  7697. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7698. auto it = ctx->device->pipeline_solve_tri_f32.find(solve_tri_pipeline_state);
  7699. if (it != ctx->device->pipeline_solve_tri_f32.end()) {
  7700. pipeline = it->second;
  7701. } else {
  7702. ctx->device->pipeline_solve_tri_f32[solve_tri_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7703. }
  7704. }
  7705. return pipeline;
  7706. }
  7707. return nullptr;
  7708. case GGML_OP_ARGMAX:
  7709. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7710. return ctx->device->pipeline_argmax_f32;
  7711. }
  7712. return nullptr;
  7713. case GGML_OP_COUNT_EQUAL:
  7714. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7715. return ctx->device->pipeline_count_equal_i32;
  7716. }
  7717. return nullptr;
  7718. case GGML_OP_IM2COL:
  7719. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7720. return ctx->device->pipeline_im2col_f32;
  7721. }
  7722. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7723. return ctx->device->pipeline_im2col_f32_f16;
  7724. }
  7725. return nullptr;
  7726. case GGML_OP_IM2COL_3D:
  7727. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7728. return ctx->device->pipeline_im2col_3d_f32;
  7729. }
  7730. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7731. return ctx->device->pipeline_im2col_3d_f32_f16;
  7732. }
  7733. return nullptr;
  7734. case GGML_OP_TIMESTEP_EMBEDDING:
  7735. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7736. return ctx->device->pipeline_timestep_embedding_f32;
  7737. }
  7738. return nullptr;
  7739. case GGML_OP_CONV_TRANSPOSE_1D:
  7740. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7741. return ctx->device->pipeline_conv_transpose_1d_f32;
  7742. }
  7743. return nullptr;
  7744. case GGML_OP_POOL_2D:
  7745. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7746. return ctx->device->pipeline_pool2d_f32;
  7747. }
  7748. return nullptr;
  7749. case GGML_OP_RWKV_WKV6:
  7750. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7751. return ctx->device->pipeline_rwkv_wkv6_f32;
  7752. }
  7753. return nullptr;
  7754. case GGML_OP_RWKV_WKV7:
  7755. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7756. return ctx->device->pipeline_rwkv_wkv7_f32;
  7757. }
  7758. return nullptr;
  7759. case GGML_OP_SSM_SCAN:
  7760. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7761. const uint32_t d_state = src0->ne[0];
  7762. if (d_state == 128) {
  7763. return ctx->device->pipeline_ssm_scan_f32_d128;
  7764. } else if (d_state == 256) {
  7765. return ctx->device->pipeline_ssm_scan_f32_d256;
  7766. }
  7767. }
  7768. return nullptr;
  7769. case GGML_OP_SSM_CONV:
  7770. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7771. return ctx->device->pipeline_ssm_conv_f32;
  7772. }
  7773. return nullptr;
  7774. case GGML_OP_OPT_STEP_ADAMW:
  7775. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7776. return ctx->device->pipeline_opt_step_adamw_f32;
  7777. }
  7778. return nullptr;
  7779. case GGML_OP_OPT_STEP_SGD:
  7780. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7781. return ctx->device->pipeline_opt_step_sgd_f32;
  7782. }
  7783. return nullptr;
  7784. case GGML_OP_LEAKY_RELU:
  7785. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7786. return ctx->device->pipeline_leaky_relu_f32;
  7787. }
  7788. return nullptr;
  7789. case GGML_OP_CONV_2D:
  7790. case GGML_OP_CONV_TRANSPOSE_2D:
  7791. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7792. uint32_t K = dst->ne[2]; // Cout
  7793. uint32_t NPQ = dst->ne[3] * dst->ne[1] * dst->ne[0]; // N * OH * OW
  7794. vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, K, NPQ);
  7795. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  7796. uint32_t KW = (uint32_t)src0->ne[0];
  7797. uint32_t KH = (uint32_t)src0->ne[1];
  7798. uint32_t s0 = (uint32_t)(ggml_get_op_params_i32(dst, 0));
  7799. uint32_t s1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 1) : s0;
  7800. uint32_t p0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0;
  7801. uint32_t p1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 3) : 0;
  7802. uint32_t d0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 4) : 1;
  7803. uint32_t d1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 5) : 1;
  7804. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7805. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7806. if (op == GGML_OP_CONV_2D) {
  7807. if (src0->type == GGML_TYPE_F32) {
  7808. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7809. } else if (src0->type == GGML_TYPE_F16) {
  7810. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7811. }
  7812. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7813. if (src0->type == GGML_TYPE_F32) {
  7814. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7815. } else if (src0->type == GGML_TYPE_F16) {
  7816. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7817. }
  7818. }
  7819. vk_pipeline pipeline = nullptr;
  7820. {
  7821. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7822. auto it = pipelines->find(conv2d_pipeline_state);
  7823. if (it != pipelines->end()) {
  7824. pipeline = it->second;
  7825. } else {
  7826. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7827. }
  7828. }
  7829. return pipeline;
  7830. }
  7831. return nullptr;
  7832. case GGML_OP_CONV_2D_DW:
  7833. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7834. if (ggml_is_contiguous(src1)) {
  7835. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7836. } else if (ggml_is_contiguous_channels(src1)) {
  7837. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7838. }
  7839. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7840. if (ggml_is_contiguous(src1)) {
  7841. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7842. } else if (ggml_is_contiguous_channels(src1)) {
  7843. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7844. }
  7845. }
  7846. return nullptr;
  7847. case GGML_OP_ADD1:
  7848. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7849. return ctx->device->pipeline_add1_f16_f16;
  7850. }
  7851. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7852. return ctx->device->pipeline_add1_f16_f32;
  7853. }
  7854. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7855. return ctx->device->pipeline_add1_f32_f32;
  7856. }
  7857. return nullptr;
  7858. case GGML_OP_ARANGE:
  7859. if (dst->type == GGML_TYPE_F32) {
  7860. return ctx->device->pipeline_arange_f32;
  7861. }
  7862. return nullptr;
  7863. case GGML_OP_FILL:
  7864. if (dst->type == GGML_TYPE_F32) {
  7865. return ctx->device->pipeline_fill_f32;
  7866. }
  7867. return nullptr;
  7868. default:
  7869. return nullptr;
  7870. }
  7871. GGML_UNUSED(src2);
  7872. }
  7873. 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) {
  7874. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7875. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7876. p.misalign_offsets = (a_offset << 16) | d_offset;
  7877. GGML_UNUSED(src1);
  7878. GGML_UNUSED(src2);
  7879. GGML_UNUSED(src3);
  7880. }
  7881. 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) {
  7882. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7883. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7884. p.misalign_offsets = (a_offset << 16) | d_offset;
  7885. GGML_UNUSED(src1);
  7886. GGML_UNUSED(src2);
  7887. GGML_UNUSED(src3);
  7888. }
  7889. 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) {
  7890. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7891. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7892. p.misalign_offsets = (a_offset << 16) | d_offset;
  7893. GGML_UNUSED(src1);
  7894. GGML_UNUSED(src2);
  7895. GGML_UNUSED(src3);
  7896. }
  7897. 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) {
  7898. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7899. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7900. p.misalign_offsets = (a_offset << 16) | d_offset;
  7901. GGML_UNUSED(src0);
  7902. GGML_UNUSED(src2);
  7903. GGML_UNUSED(src3);
  7904. }
  7905. 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) {
  7906. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7907. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7908. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7909. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7910. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7911. GGML_UNUSED(src2);
  7912. GGML_UNUSED(src3);
  7913. }
  7914. 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) {
  7915. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7916. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7917. p.a_offset = a_offset;
  7918. p.d_offset = d_offset;
  7919. GGML_UNUSED(src1);
  7920. GGML_UNUSED(src2);
  7921. GGML_UNUSED(src3);
  7922. }
  7923. template<typename PC>
  7924. 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) {
  7925. 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];
  7926. if (src1 != nullptr) {
  7927. 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];
  7928. }
  7929. if (src2 != nullptr) {
  7930. 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];
  7931. }
  7932. if (src3 != nullptr) {
  7933. 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];
  7934. }
  7935. 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];
  7936. std::cerr << "), " << ggml_op_name(op) << ")");
  7937. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7938. GGML_ASSERT(dst->buffer != nullptr);
  7939. const uint64_t ne00 = src0->ne[0];
  7940. const uint64_t ne01 = src0->ne[1];
  7941. const uint64_t ne02 = src0->ne[2];
  7942. const uint64_t ne03 = src0->ne[3];
  7943. const bool use_src1 = src1 != nullptr;
  7944. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7945. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7946. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7947. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7948. const bool use_src2 = src2 != nullptr;
  7949. const bool use_src3 = src3 != nullptr;
  7950. init_pushconst_fastdiv(pc);
  7951. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7952. if (pipeline == nullptr) {
  7953. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7954. if (src1 != nullptr) {
  7955. std::cerr << " and " << ggml_type_name(src1->type);
  7956. }
  7957. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7958. GGML_ABORT("fatal error");
  7959. }
  7960. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7961. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true);
  7962. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, true) : vk_subbuffer{};
  7963. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, true) : vk_subbuffer{};
  7964. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, true) : vk_subbuffer{};
  7965. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
  7966. // Compute misalignment offset for descriptors and store it in in push constants.
  7967. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7968. std::array<uint32_t, 3> elements;
  7969. switch (op) {
  7970. case GGML_OP_NORM:
  7971. case GGML_OP_RMS_NORM_BACK:
  7972. case GGML_OP_L2_NORM:
  7973. case GGML_OP_SOFT_MAX:
  7974. case GGML_OP_SOFT_MAX_BACK:
  7975. case GGML_OP_SUM_ROWS:
  7976. case GGML_OP_CUMSUM:
  7977. case GGML_OP_MEAN:
  7978. case GGML_OP_ARGMAX:
  7979. {
  7980. const uint32_t nr = ggml_nrows(src0);
  7981. if (nr > 262144) {
  7982. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7983. } else if (nr > 512) {
  7984. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7985. } else {
  7986. elements = { nr, 1, 1 };
  7987. }
  7988. } break;
  7989. case GGML_OP_SOLVE_TRI:
  7990. {
  7991. uint32_t nr = (uint32_t)(ne02 * ne03);
  7992. if (nr > 262144) {
  7993. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7994. } else if (nr > 512) {
  7995. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7996. } else {
  7997. elements = { nr, 1, 1 };
  7998. }
  7999. }
  8000. break;
  8001. case GGML_OP_RMS_NORM:
  8002. if (ctx->do_add_rms_partials) {
  8003. // Run one element per thread, 128 threads per workgroup
  8004. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  8005. } else {
  8006. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  8007. }
  8008. break;
  8009. case GGML_OP_SUM:
  8010. // We use GGML_OP_SUM_ROWS with 1 row.
  8011. elements = { 1, 1, 1 };
  8012. break;
  8013. case GGML_OP_GROUP_NORM:
  8014. {
  8015. const uint32_t num_groups = dst->op_params[0];
  8016. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  8017. } break;
  8018. case GGML_OP_DIAG_MASK_INF:
  8019. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  8020. break;
  8021. case GGML_OP_ROPE:
  8022. case GGML_OP_ROPE_BACK:
  8023. {
  8024. uint32_t nrows = (uint32_t)ggml_nrows(src0);
  8025. uint32_t z = 1;
  8026. if (nrows > ctx->device->properties.limits.maxComputeWorkGroupCount[0]) {
  8027. z = CEIL_DIV(nrows, 32768);
  8028. nrows = 32768;
  8029. }
  8030. elements = { nrows, (uint32_t)ne00, z };
  8031. } break;
  8032. case GGML_OP_GET_ROWS:
  8033. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  8034. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8035. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8036. break;
  8037. case GGML_OP_ARGSORT:
  8038. GGML_ASSERT(0);
  8039. break;
  8040. case GGML_OP_IM2COL:
  8041. {
  8042. const bool is_2D = dst->op_params[6] == 1;
  8043. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8044. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8045. const uint32_t KW = src0->ne[0];
  8046. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8047. const uint32_t OW = dst->ne[1];
  8048. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  8049. elements = { OW * KW * KH, OH, batch * IC };
  8050. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8051. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8052. } break;
  8053. case GGML_OP_IM2COL_3D:
  8054. {
  8055. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  8056. const uint32_t N = ne13 / IC;
  8057. const uint32_t KD = ne02;
  8058. const uint32_t KH = ne01;
  8059. const uint32_t KW = ne00;
  8060. const uint32_t OD = dst->ne[3] / N;
  8061. const uint32_t OH = dst->ne[2];
  8062. const uint32_t OW = dst->ne[1];
  8063. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  8064. const uint32_t N_OD_OH = N*OD*OH;
  8065. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  8066. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8067. } break;
  8068. case GGML_OP_TIMESTEP_EMBEDDING:
  8069. {
  8070. const uint32_t dim = dst->op_params[0];
  8071. uint32_t half_ceil = (dim + 1) / 2;
  8072. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  8073. } break;
  8074. case GGML_OP_CONV_TRANSPOSE_1D:
  8075. {
  8076. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  8077. } break;
  8078. case GGML_OP_POOL_2D:
  8079. {
  8080. const uint32_t N = dst->ne[3];
  8081. const uint32_t OC = dst->ne[2];
  8082. const uint32_t OH = dst->ne[1];
  8083. const uint32_t OW = dst->ne[0];
  8084. elements = { N * OC * OH * OW, 1, 1};
  8085. } break;
  8086. case GGML_OP_CONV_2D:
  8087. case GGML_OP_CONV_TRANSPOSE_2D:
  8088. if constexpr (std::is_same_v<PC, vk_op_conv2d_push_constants>) {
  8089. const uint32_t NPQ = pc.N * pc.OH * pc.OW;
  8090. const vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, pc.Cout, NPQ);
  8091. const uint32_t NPQ_blocks = CEIL_DIV(NPQ, vk_conv_block_sizes[shape].NPQ);
  8092. elements = { pc.Cout, NPQ_blocks, 1 };
  8093. if (elements[1] > 512) {
  8094. elements[2] = CEIL_DIV(elements[1], 512);
  8095. elements[1] = 512;
  8096. }
  8097. } else {
  8098. GGML_ABORT("invalid push constant type for CONV_2D");
  8099. }
  8100. break;
  8101. case GGML_OP_ADD:
  8102. case GGML_OP_SUB:
  8103. case GGML_OP_DIV:
  8104. case GGML_OP_MUL:
  8105. case GGML_OP_ADD1:
  8106. case GGML_OP_ARANGE:
  8107. case GGML_OP_FILL:
  8108. case GGML_OP_SCALE:
  8109. case GGML_OP_SQR:
  8110. case GGML_OP_SQRT:
  8111. case GGML_OP_SIN:
  8112. case GGML_OP_COS:
  8113. case GGML_OP_LOG:
  8114. case GGML_OP_TRI:
  8115. case GGML_OP_DIAG:
  8116. case GGML_OP_CLAMP:
  8117. case GGML_OP_PAD:
  8118. case GGML_OP_ROLL:
  8119. case GGML_OP_REPEAT:
  8120. case GGML_OP_REPEAT_BACK:
  8121. case GGML_OP_CPY:
  8122. case GGML_OP_CONCAT:
  8123. case GGML_OP_UPSCALE:
  8124. case GGML_OP_UNARY:
  8125. case GGML_OP_GLU:
  8126. case GGML_OP_CONV_2D_DW:
  8127. {
  8128. uint32_t ne = ggml_nelements(dst);
  8129. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8130. // Convert from number of logical elements to 2- or 4-byte units.
  8131. ne /= ggml_blck_size(src0->type);
  8132. if ((ggml_type_size(src0->type) % 4) == 0) {
  8133. ne *= ggml_type_size(src0->type) / 4;
  8134. } else {
  8135. ne *= ggml_type_size(src0->type) / 2;
  8136. }
  8137. }
  8138. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  8139. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  8140. // So divide by block size here before splitting into 512x512 groups.
  8141. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8142. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  8143. }
  8144. if (ne > 262144) {
  8145. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8146. } else if (ne > 512) {
  8147. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8148. } else {
  8149. elements = { ne, 1, 1 };
  8150. }
  8151. if (pipeline == ctx->device->pipeline_cpy_transpose_32 ||
  8152. pipeline == ctx->device->pipeline_cpy_transpose_16) {
  8153. // 32x32 tiles
  8154. elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32);
  8155. elements[1] = (uint32_t)CEIL_DIV(dst->ne[1], 32);
  8156. elements[2] = (uint32_t)(dst->ne[2]*dst->ne[3]);
  8157. elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]);
  8158. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8159. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8160. }
  8161. } break;
  8162. case GGML_OP_ADD_ID:
  8163. {
  8164. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  8165. } break;
  8166. case GGML_OP_SET_ROWS:
  8167. {
  8168. uint32_t ne = ggml_nelements(src0);
  8169. if (ggml_is_quantized(dst->type)) {
  8170. // quants run 32 threads each doing QUANT_K elements
  8171. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  8172. } else {
  8173. // scalar types do one element per thread, running 512 threads
  8174. ne = CEIL_DIV(ne, 512);
  8175. }
  8176. if (ne > 262144) {
  8177. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8178. } else if (ne > 512) {
  8179. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8180. } else {
  8181. elements = { ne, 1, 1 };
  8182. }
  8183. }
  8184. break;
  8185. case GGML_OP_SSM_CONV:
  8186. {
  8187. const uint32_t nr = src0->ne[1];
  8188. const uint32_t n_t = dst->ne[1];
  8189. const uint32_t n_s = dst->ne[2];
  8190. elements = { nr, n_t, n_s };
  8191. }
  8192. break;
  8193. default:
  8194. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  8195. break;
  8196. }
  8197. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  8198. vk_subbuffer a_buf = src0_buf;
  8199. if (ctx->do_add_rms_partials) {
  8200. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  8201. }
  8202. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8203. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  8204. } else if (op == GGML_OP_GLU) {
  8205. // Empty src1 is possible in glu, but the shader needs a buffer
  8206. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  8207. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  8208. } else if (op == GGML_OP_SOFT_MAX) {
  8209. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  8210. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  8211. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  8212. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  8213. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  8214. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  8215. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  8216. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  8217. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  8218. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  8219. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  8220. // buffer device address path doesn't use dst buffer
  8221. dst_buf.size = 1;
  8222. }
  8223. // im2col uses only src1 and dst buffers
  8224. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  8225. } else if (op == GGML_OP_COUNT_EQUAL) {
  8226. // count_equal assumes that destination buffer is initialized with zeroes
  8227. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  8228. ggml_vk_sync_buffers(ctx, subctx);
  8229. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  8230. } else if (op == GGML_OP_OPT_STEP_SGD) {
  8231. // OPT_STEP_SGD works on src0, it does not need dst
  8232. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  8233. } else if (use_src3) {
  8234. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  8235. } else if (use_src2) {
  8236. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  8237. } else if (use_src1) {
  8238. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  8239. } else {
  8240. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  8241. }
  8242. }
  8243. 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) {
  8244. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8245. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8246. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8247. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  8248. (uint32_t)ggml_nelements(src0),
  8249. (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,
  8250. (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,
  8251. (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,
  8252. 0,
  8253. 0.0f, 0.0f, 0,
  8254. });
  8255. }
  8256. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8257. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8258. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8259. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8260. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  8261. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  8262. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  8263. int offset = dst->op_params[3] / 4; // offset in bytes
  8264. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  8265. (uint32_t)ggml_nelements(src0),
  8266. (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,
  8267. (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,
  8268. (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,
  8269. 0,
  8270. 0.0f, 0.0f, offset,
  8271. });
  8272. }
  8273. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8274. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  8275. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  8276. // Make a list of all the tensors used by the op.
  8277. // Last element of the list is the dest tensor.
  8278. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  8279. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  8280. uint32_t num_tensors = num_srcs + 1;
  8281. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  8282. tensors[0] = first_node->src[0];
  8283. tensors[1] = first_node->src[1];
  8284. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  8285. // check whether the previous result is src[0] or src[1]
  8286. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  8287. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  8288. } else {
  8289. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  8290. }
  8291. }
  8292. tensors[num_srcs] = dst;
  8293. vk_op_multi_add_push_constants pc;
  8294. pc.ne20 = (uint32_t)dst->ne[0];
  8295. pc.ne21 = (uint32_t)dst->ne[1];
  8296. pc.ne22 = (uint32_t)dst->ne[2];
  8297. pc.ne23 = (uint32_t)dst->ne[3];
  8298. for (uint32_t i = 0; i < num_tensors; ++i) {
  8299. const ggml_tensor *t = tensors[i];
  8300. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  8301. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  8302. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  8303. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  8304. }
  8305. pc.rms_partials = ctx->do_add_rms_partials;
  8306. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  8307. if (pipeline == nullptr) {
  8308. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  8309. GGML_ABORT("fatal error");
  8310. }
  8311. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8312. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  8313. vk_buffer buf[MAX_PARAMETER_COUNT];
  8314. size_t offset[MAX_PARAMETER_COUNT];
  8315. bool uma[MAX_PARAMETER_COUNT];
  8316. for (uint32_t i = 0; i < num_tensors; ++i) {
  8317. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8318. buf[i] = nullptr;
  8319. offset[i] = 0;
  8320. uma[i] = false;
  8321. if (ctx->device->uma) {
  8322. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8323. uma[i] = buf[i] != nullptr;
  8324. }
  8325. if (!uma[i]) {
  8326. buf[i] = buf_ctx[i]->dev_buffer;
  8327. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8328. }
  8329. GGML_ASSERT(buf[i] != nullptr);
  8330. }
  8331. // If any remaining descriptors are unused, just point them at src[0]
  8332. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  8333. buf[i] = buf[0];
  8334. offset[i] = 0;
  8335. }
  8336. if (ctx->do_add_rms_partials) {
  8337. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  8338. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  8339. }
  8340. std::array<uint32_t, 3> elements;
  8341. uint32_t ne = ggml_nelements(dst);
  8342. if (ne > 262144) {
  8343. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8344. } else if (ne > 512) {
  8345. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8346. } else {
  8347. elements = { ne, 1, 1 };
  8348. }
  8349. static_assert(MAX_PARAMETER_COUNT == 12);
  8350. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8351. {
  8352. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8353. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8354. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8355. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8356. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8357. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8358. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8359. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  8360. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  8361. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  8362. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  8363. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  8364. }, pc, elements);
  8365. }
  8366. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8367. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8368. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8369. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8370. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  8371. (uint32_t)ggml_nelements(src0),
  8372. (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,
  8373. (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,
  8374. (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,
  8375. 0,
  8376. 0.0f, 0.0f, ctx->do_add_rms_partials,
  8377. });
  8378. }
  8379. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8380. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8381. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8382. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8383. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  8384. (uint32_t)ggml_nelements(src0),
  8385. (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,
  8386. (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,
  8387. (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,
  8388. 0,
  8389. 0.0f, 0.0f, 0,
  8390. });
  8391. }
  8392. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8393. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8394. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8395. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8396. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  8397. (uint32_t)ggml_nelements(src0),
  8398. (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,
  8399. (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,
  8400. (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,
  8401. 0,
  8402. 0.0f, 0.0f, 0,
  8403. });
  8404. }
  8405. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8406. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8407. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8408. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8409. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  8410. (uint32_t)ggml_nelements(src0),
  8411. (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,
  8412. (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,
  8413. (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,
  8414. 0,
  8415. 0.0f, 0.0f, 0,
  8416. });
  8417. }
  8418. 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) {
  8419. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8420. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8421. const uint32_t src2_type_size = ggml_type_size(src2->type);
  8422. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  8423. (uint32_t)dst->ne[0],
  8424. (uint32_t)dst->ne[1],
  8425. (uint32_t)src0->nb[1] / src0_type_size,
  8426. (uint32_t)src0->nb[2] / src0_type_size,
  8427. (uint32_t)src1->nb[1] / src1_type_size,
  8428. (uint32_t)src2->nb[1] / src2_type_size,
  8429. });
  8430. }
  8431. 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) {
  8432. GGML_ASSERT(version == 6 || version == 7);
  8433. int num_srcs = version == 6 ? 6 : 7;
  8434. for (int i = 0; i < num_srcs; i++) {
  8435. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  8436. }
  8437. GGML_ASSERT(dst->buffer != nullptr);
  8438. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8439. GGML_ASSERT(pipeline != nullptr);
  8440. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8441. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8442. vk_subbuffer src_buf[7] = {};
  8443. for (int i = 0; i < num_srcs; i++) {
  8444. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8445. }
  8446. std::array<uint32_t, 3> elements = {
  8447. (uint32_t)(pc.B * pc.H),
  8448. 1,
  8449. 1
  8450. };
  8451. if (version == 6) {
  8452. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8453. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  8454. pc, elements);
  8455. } else if (version == 7) {
  8456. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8457. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8458. pc, elements);
  8459. } else {
  8460. // shouldn't happen
  8461. GGML_ASSERT(false);
  8462. }
  8463. }
  8464. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8465. const size_t seq_length = dst->src[0]->ne[2];
  8466. const size_t n_embed = dst->ne[0];
  8467. const size_t n_heads = dst->src[0]->ne[1];
  8468. const size_t n_seqs = dst->src[5]->ne[1];
  8469. ggml_vk_op_f32_wkv(
  8470. ctx, subctx, dst,
  8471. {
  8472. (uint32_t)n_seqs,
  8473. (uint32_t)seq_length,
  8474. (uint32_t)n_embed,
  8475. (uint32_t)n_heads,
  8476. },
  8477. 6
  8478. );
  8479. }
  8480. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8481. const size_t seq_length = dst->src[0]->ne[2];
  8482. const size_t n_embed = dst->ne[0];
  8483. const size_t n_heads = dst->src[0]->ne[1];
  8484. const size_t n_seqs = dst->src[6]->ne[1];
  8485. ggml_vk_op_f32_wkv(
  8486. ctx, subctx, dst,
  8487. {
  8488. (uint32_t)n_seqs,
  8489. (uint32_t)seq_length,
  8490. (uint32_t)n_embed,
  8491. (uint32_t)n_heads,
  8492. },
  8493. 7
  8494. );
  8495. }
  8496. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8497. const ggml_tensor * src0 = dst->src[0];
  8498. const ggml_tensor * src1 = dst->src[1];
  8499. const ggml_tensor * src2 = dst->src[2];
  8500. const ggml_tensor * src3 = dst->src[3];
  8501. const ggml_tensor * src4 = dst->src[4];
  8502. const ggml_tensor * src5 = dst->src[5];
  8503. GGML_ASSERT(dst->buffer != nullptr);
  8504. const uint32_t head_dim = src0->ne[1];
  8505. const uint32_t n_head = src1->ne[1];
  8506. const uint32_t n_group = src4->ne[1];
  8507. const uint32_t n_tok = src1->ne[2];
  8508. const uint32_t n_seq = src1->ne[3];
  8509. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8510. GGML_ASSERT(is_mamba2);
  8511. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8512. GGML_ASSERT(pipeline != nullptr);
  8513. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8514. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8515. const vk_op_ssm_scan_push_constants pc = {
  8516. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8517. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8518. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8519. (uint32_t)src3->nb[1],
  8520. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8521. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8522. (uint32_t)s_off,
  8523. n_head, head_dim, n_group, n_tok
  8524. };
  8525. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8526. vk_subbuffer src_buf[7] = {};
  8527. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8528. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8529. }
  8530. std::array<uint32_t, 3> elements;
  8531. const int splitH = 16;
  8532. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8533. const uint32_t num_workgroups_y = n_seq;
  8534. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8535. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8536. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8537. pc, elements);
  8538. }
  8539. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8540. const ggml_tensor * src0 = dst->src[0];
  8541. const ggml_tensor * src1 = dst->src[1];
  8542. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8543. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8544. (uint32_t)src1->nb[1],
  8545. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8546. (uint32_t)src1->ne[0],
  8547. (uint32_t)src0->ne[0],
  8548. (uint32_t)src0->ne[1],
  8549. (uint32_t)dst->ne[1],
  8550. (uint32_t)dst->ne[2],
  8551. });
  8552. }
  8553. 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) {
  8554. const ggml_tensor * x = dst->src[0];
  8555. const ggml_tensor * g = dst->src[1];
  8556. const ggml_tensor * gm = dst->src[2];
  8557. const ggml_tensor * gv = dst->src[3];
  8558. const ggml_tensor * p = dst->src[4];
  8559. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8560. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8561. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8562. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8563. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8564. GGML_ASSERT(dst->buffer != nullptr);
  8565. GGML_ASSERT(ggml_is_contiguous(x));
  8566. GGML_ASSERT(ggml_is_contiguous(g));
  8567. GGML_ASSERT(ggml_is_contiguous(gm));
  8568. GGML_ASSERT(ggml_is_contiguous(gv));
  8569. GGML_ASSERT(ggml_is_contiguous(p));
  8570. GGML_ASSERT(ggml_are_same_shape(x, g));
  8571. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8572. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8573. GGML_ASSERT(ggml_nelements(p) == 7);
  8574. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8575. GGML_ASSERT(pipeline != nullptr);
  8576. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8577. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8578. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8579. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8580. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8581. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8582. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8583. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8584. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8585. pc, elements);
  8586. }
  8587. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8588. const size_t n = ggml_nelements(dst->src[0]);
  8589. ggml_vk_op_f32_opt_step_adamw(
  8590. ctx, subctx, dst,
  8591. { (uint32_t)n, 0, 0.0f, 0.0f, 0.0f, 0.0f }
  8592. );
  8593. }
  8594. 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) {
  8595. const size_t n = ggml_nelements(dst->src[0]);
  8596. 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, 0.0f, 0.0f });
  8597. }
  8598. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8599. int * op_params = (int *)dst->op_params;
  8600. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8601. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8602. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8603. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8604. (uint32_t)ggml_nelements(dst),
  8605. (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,
  8606. (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,
  8607. (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,
  8608. 0,
  8609. 0.0f, 0.0f, op_params[0],
  8610. });
  8611. }
  8612. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8613. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8614. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8615. GGML_TENSOR_UNARY_OP_LOCALS
  8616. float sf0 = (float)ne0 / ne00;
  8617. float sf1 = (float)ne1 / ne01;
  8618. float sf2 = (float)ne2 / ne02;
  8619. float sf3 = (float)ne3 / ne03;
  8620. float pixel_offset = 0.5f;
  8621. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8622. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8623. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8624. pixel_offset = 0.0f;
  8625. }
  8626. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8627. (uint32_t)ggml_nelements(dst), 0, 0,
  8628. (uint32_t)ne00, (uint32_t)ne01,
  8629. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8630. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8631. sf0, sf1, sf2, sf3, pixel_offset
  8632. });
  8633. }
  8634. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8635. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8636. p.param1 = ggml_get_op_params_f32(dst, 0);
  8637. p.param2 = ggml_get_op_params_f32(dst, 1);
  8638. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8639. }
  8640. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8641. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8642. }
  8643. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8644. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8645. }
  8646. static void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8647. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8648. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8649. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8650. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, {
  8651. (uint32_t)ggml_nelements(src0),
  8652. (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,
  8653. (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,
  8654. (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,
  8655. 0,
  8656. 0.0f, 0.0f, 0,
  8657. });
  8658. }
  8659. static void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8660. VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8661. vk_op_push_constants pc = {
  8662. (uint32_t)ggml_nelements(dst),
  8663. 1,
  8664. ggml_get_op_params_f32(dst, 0),
  8665. ggml_get_op_params_f32(dst, 2),
  8666. 0.0f, 0.0f,
  8667. };
  8668. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_ARANGE);
  8669. GGML_ASSERT(pipeline != nullptr);
  8670. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8671. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8672. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8673. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8674. }
  8675. static void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8676. VK_LOG_DEBUG("ggml_vk_fill(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8677. vk_op_push_constants pc = {
  8678. (uint32_t)ggml_nelements(dst),
  8679. 1,
  8680. ggml_get_op_params_f32(dst, 0),
  8681. 0.0f,
  8682. 0.0f, 0.0f,
  8683. };
  8684. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_FILL);
  8685. GGML_ASSERT(pipeline != nullptr);
  8686. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8687. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8688. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8689. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8690. }
  8691. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8692. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8693. }
  8694. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8695. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8696. }
  8697. static void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8698. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst));
  8699. }
  8700. static void ggml_vk_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8701. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8702. p.param1 = ggml_get_op_params_f32(dst, 0);
  8703. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TRI, std::move(p));
  8704. }
  8705. static void ggml_vk_diag(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8706. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8707. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG, std::move(p));
  8708. }
  8709. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8710. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8711. p.param1 = ggml_get_op_params_f32(dst, 0);
  8712. p.param2 = ggml_get_op_params_f32(dst, 1);
  8713. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8714. }
  8715. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8716. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8717. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8718. }
  8719. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8720. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8721. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8722. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8723. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8724. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8725. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8726. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8727. memcpy(&p.param1, &s01_packed, sizeof(float));
  8728. memcpy(&p.param2, &s23_packed, sizeof(float));
  8729. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8730. }
  8731. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8732. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8733. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8734. }
  8735. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8736. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8737. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8738. }
  8739. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8740. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8741. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8742. // Convert from number of logical elements to 2- or 4-byte units.
  8743. ne /= ggml_blck_size(src0->type);
  8744. if ((ggml_type_size(src0->type) % 4) == 0) {
  8745. ne *= ggml_type_size(src0->type) / 4;
  8746. } else {
  8747. ne *= ggml_type_size(src0->type) / 2;
  8748. }
  8749. }
  8750. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8751. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8752. }
  8753. 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) {
  8754. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8755. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8756. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8757. // Skip empty skip_rows operations. For most ops the empty check at the start
  8758. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8759. // with empty srcs.
  8760. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8761. return;
  8762. }
  8763. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8764. (uint32_t)ggml_nelements(src0),
  8765. (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,
  8766. (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,
  8767. (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,
  8768. 0,
  8769. 0.0f, 0.0f, 0,
  8770. });
  8771. }
  8772. 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) {
  8773. 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, 0.0f, 0.0f });
  8774. }
  8775. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8776. float * op_params = (float *)dst->op_params;
  8777. 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, 0.0f, 0.0f });
  8778. }
  8779. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8780. const int * int_op_params = (const int *)dst->op_params;
  8781. const float * float_op_params = (const float *)dst->op_params;
  8782. const uint32_t num_groups = int_op_params[0];
  8783. const float eps = float_op_params[1];
  8784. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8785. 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, 0.0f, 0.0f });
  8786. }
  8787. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8788. const uint32_t ne = (uint32_t)node->ne[0];
  8789. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8790. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8791. return num_partials;
  8792. }
  8793. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8794. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8795. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8796. return num_bytes;
  8797. }
  8798. 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) {
  8799. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8800. const int mode = ((const int32_t *) dst->op_params)[2];
  8801. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8802. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8803. const float freq_base = ((const float *) dst->op_params)[5];
  8804. const float freq_scale = ((const float *) dst->op_params)[6];
  8805. const float ext_factor = ((const float *) dst->op_params)[7];
  8806. const float attn_factor = ((const float *) dst->op_params)[8];
  8807. const float beta_fast = ((const float *) dst->op_params)[9];
  8808. const float beta_slow = ((const float *) dst->op_params)[10];
  8809. int sections[4] {};
  8810. if (mode & GGML_ROPE_TYPE_MROPE) {
  8811. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8812. }
  8813. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8814. float corr_dims[2];
  8815. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8816. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8817. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8818. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8819. vk_op_rope_push_constants rope {
  8820. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8821. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8822. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8823. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8824. };
  8825. return rope;
  8826. }
  8827. 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) {
  8828. ggml_tensor * dst;
  8829. const ggml_tensor * src0;
  8830. const ggml_tensor * src1;
  8831. if (ctx->num_additional_fused_ops > 0) {
  8832. // fused rms_norm + mul
  8833. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8834. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8835. dst = mul;
  8836. src0 = cgraph->nodes[node_idx]->src[0];
  8837. src1 = other_src;
  8838. } else {
  8839. dst = cgraph->nodes[node_idx];
  8840. src0 = src1 = dst->src[0];
  8841. }
  8842. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8843. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8844. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8845. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8846. vk_op_binary_push_constants bin {
  8847. (uint32_t)ggml_nelements(src0),
  8848. (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,
  8849. (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,
  8850. (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,
  8851. 0,
  8852. op_params[0], 0.0f, (int32_t)param3,
  8853. };
  8854. // more than one fused op means rms_norm+mul+rope
  8855. if (ctx->num_additional_fused_ops > 1) {
  8856. static constexpr uint32_t max_tensors = 7;
  8857. const ggml_tensor *tensors[max_tensors] {};
  8858. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8859. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8860. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8861. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8862. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8863. tensors[0] = rms->src[0];
  8864. tensors[1] = other_src;
  8865. tensors[2] = mul;
  8866. tensors[3] = rope->src[1]; // pos
  8867. tensors[4] = rope->src[2]; // ff
  8868. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8869. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8870. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8871. vk_op_rms_norm_mul_rope_push_constants pc;
  8872. pc.bin = bin;
  8873. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8874. 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;
  8875. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8876. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8877. vk_buffer buf[max_tensors];
  8878. size_t offset[max_tensors];
  8879. bool uma[max_tensors];
  8880. for (uint32_t i = 0; i < max_tensors; ++i) {
  8881. if (!tensors[i]) {
  8882. // If any remaining descriptors are unused, just point them at src[0]
  8883. buf[i] = buf[0];
  8884. offset[i] = 0;
  8885. continue;
  8886. }
  8887. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8888. buf[i] = nullptr;
  8889. offset[i] = 0;
  8890. uma[i] = false;
  8891. if (ctx->device->uma) {
  8892. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8893. uma[i] = buf[i] != nullptr;
  8894. }
  8895. if (!uma[i]) {
  8896. buf[i] = buf_ctx[i]->dev_buffer;
  8897. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8898. }
  8899. GGML_ASSERT(buf[i] != nullptr);
  8900. }
  8901. std::array<uint32_t, 3> elements;
  8902. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8903. static_assert(max_tensors == 7);
  8904. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8905. {
  8906. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8907. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8908. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8909. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8910. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8911. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8912. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8913. }, pc, elements);
  8914. } else {
  8915. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8916. }
  8917. if (ctx->do_add_rms_partials_offset_calculation) {
  8918. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8919. ctx->do_add_rms_partials = false;
  8920. ctx->do_add_rms_partials_offset_calculation = false;
  8921. }
  8922. }
  8923. 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) {
  8924. float * op_params = (float *)dst->op_params;
  8925. 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, 0.0f, 0.0f });
  8926. }
  8927. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8928. float * op_params = (float *)dst->op_params;
  8929. 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, 0.0f, 0.0f });
  8930. }
  8931. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8932. 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, 0.0f, 0.0f });
  8933. }
  8934. static void ggml_vk_xielu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8935. float * op_params = (float *)dst->op_params;
  8936. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY,
  8937. {
  8938. (uint32_t)ggml_nelements(src0), 0,
  8939. op_params[1], op_params[2], op_params[3], op_params[4]
  8940. }
  8941. );
  8942. }
  8943. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8944. const float * op_params_f = (const float *)dst->op_params;
  8945. const bool swapped = (bool)dst->op_params[1];
  8946. const bool split = src1 != nullptr;
  8947. const float alpha = op_params_f[2];
  8948. const float limit = op_params_f[3];
  8949. GGML_ASSERT(ggml_is_contiguous(src0));
  8950. if (!split) {
  8951. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8952. } else {
  8953. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8954. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8955. GGML_ASSERT(src0->type == src1->type);
  8956. }
  8957. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8958. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8959. {
  8960. (uint32_t)ggml_nelements(dst),
  8961. (uint32_t)src0->ne[0],
  8962. (uint32_t)dst->ne[0],
  8963. mode,
  8964. alpha,
  8965. limit
  8966. });
  8967. }
  8968. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8969. int32_t * op_params = (int32_t *)dst->op_params;
  8970. 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] });
  8971. }
  8972. 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) {
  8973. float * op_params = (float *)dst->op_params;
  8974. float scale = op_params[0];
  8975. float max_bias = op_params[1];
  8976. const uint32_t ncols = (uint32_t)src0->ne[0];
  8977. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8978. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8979. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8980. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8981. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8982. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8983. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8984. const uint32_t n_head_kv = src0->ne[2];
  8985. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8986. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8987. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8988. vk_op_soft_max_push_constants pc {
  8989. ncols,
  8990. src1 != nullptr ? nrows_y : (uint32_t)0,
  8991. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8992. ne12, ne13,
  8993. nb11, nb12, nb13,
  8994. scale, max_bias,
  8995. m0, m1,
  8996. n_head_log2,
  8997. nrows_x,
  8998. src2 != nullptr
  8999. };
  9000. if (ncols <= 16384) {
  9001. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, std::move(pc));
  9002. } else {
  9003. vk_subbuffer buf_a = ggml_vk_tensor_subbuffer(ctx, src0);
  9004. vk_subbuffer buf_b = src1 ? ggml_vk_tensor_subbuffer(ctx, src1) : buf_a;
  9005. vk_subbuffer buf_c = src2 ? ggml_vk_tensor_subbuffer(ctx, src2) : buf_a;
  9006. vk_subbuffer buf_d = ggml_vk_tensor_subbuffer(ctx, dst);
  9007. uint32_t elems_per_wg = 128 * 4;
  9008. uint32_t num_wgs = CEIL_DIV(ncols, elems_per_wg);
  9009. size_t tmp_size = num_wgs * nrows_x * sizeof(float);
  9010. if (ctx->prealloc_size_x < tmp_size) {
  9011. ctx->prealloc_size_x = tmp_size;
  9012. ggml_vk_preallocate_buffers(ctx, subctx);
  9013. }
  9014. if (ctx->prealloc_size_y < tmp_size) {
  9015. ctx->prealloc_size_y = tmp_size;
  9016. ggml_vk_preallocate_buffers(ctx, subctx);
  9017. }
  9018. if (ctx->prealloc_x_need_sync || ctx->prealloc_y_need_sync) {
  9019. ggml_vk_sync_buffers(ctx, subctx);
  9020. }
  9021. vk_subbuffer buf_x = { ctx->prealloc_x, 0, tmp_size };
  9022. vk_subbuffer buf_y = { ctx->prealloc_y, 0, tmp_size };
  9023. std::array<uint32_t, 3> elements = { num_wgs, nrows_x, 1 };
  9024. vk_pipeline pipeline1 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large1_f32_f16 : ctx->device->pipeline_soft_max_large1_f32;
  9025. vk_pipeline pipeline2 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large2_f32_f16 : ctx->device->pipeline_soft_max_large2_f32;
  9026. vk_pipeline pipeline3 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large3_f32_f16 : ctx->device->pipeline_soft_max_large3_f32;
  9027. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  9028. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  9029. ggml_pipeline_request_descriptor_sets(ctx, pipeline3, 1);
  9030. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9031. ggml_vk_sync_buffers(ctx, subctx);
  9032. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9033. ggml_vk_sync_buffers(ctx, subctx);
  9034. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline3, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9035. ctx->prealloc_x_need_sync = true;
  9036. ctx->prealloc_y_need_sync = true;
  9037. }
  9038. }
  9039. 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) {
  9040. float * op_params = (float *)dst->op_params;
  9041. 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], 0.0f, 0.0f });
  9042. }
  9043. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  9044. topk_moe_mode mode = ctx->fused_topk_moe_mode;
  9045. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  9046. ggml_tensor * bias = (mode == TOPK_MOE_SIGMOID_NORM_BIAS) ? cgraph->nodes[node_idx + 2]->src[1] : logits;
  9047. ggml_tensor * weights = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  9048. ggml_tensor * ids = (mode == TOPK_MOE_SIGMOID_NORM_BIAS) ? cgraph->nodes[node_idx + 4] :
  9049. (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] :
  9050. cgraph->nodes[node_idx + 3];
  9051. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  9052. GGML_ASSERT(bias->type == GGML_TYPE_F32);
  9053. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  9054. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  9055. const int n_experts = logits->ne[0];
  9056. const int n_rows = logits->ne[1];
  9057. const int n_expert_used = weights->ne[1];
  9058. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  9059. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  9060. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9061. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  9062. vk_subbuffer bias_buf = ggml_vk_tensor_subbuffer(ctx, bias);
  9063. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  9064. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  9065. vk_op_topk_moe_push_constants pc {};
  9066. pc.n_rows = n_rows;
  9067. pc.n_experts_push = n_experts;
  9068. pc.n_expert_used = n_expert_used;
  9069. pc.clamp_min = -std::numeric_limits<float>::infinity();
  9070. pc.clamp_max = std::numeric_limits<float>::infinity();
  9071. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  9072. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  9073. GGML_ASSERT(clamp->op == GGML_OP_CLAMP);
  9074. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  9075. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  9076. }
  9077. if (mode == TOPK_MOE_SIGMOID_NORM_BIAS) {
  9078. ggml_tensor * clamp = cgraph->nodes[node_idx + 8];
  9079. GGML_ASSERT(clamp->op == GGML_OP_CLAMP);
  9080. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  9081. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  9082. }
  9083. #define GATING_FUNC_SOFTMAX 0
  9084. #define GATING_FUNC_SIGMOID 1
  9085. #define GATING_FUNC_SOFTMAX_WEIGHT 2
  9086. pc.gating_func = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? GATING_FUNC_SIGMOID :
  9087. mode == TOPK_MOE_LATE_SOFTMAX ? GATING_FUNC_SOFTMAX_WEIGHT :
  9088. GATING_FUNC_SOFTMAX;
  9089. pc.has_bias = mode == TOPK_MOE_SIGMOID_NORM_BIAS;
  9090. pc.with_norm = mode == TOPK_MOE_EARLY_SOFTMAX_NORM || mode == TOPK_MOE_SIGMOID_NORM_BIAS;
  9091. if (ctx->fused_topk_moe_scale) {
  9092. GGML_ASSERT(weights->op == GGML_OP_SCALE);
  9093. pc.output_scale = ggml_get_op_params_f32(weights, 0);
  9094. pc.output_bias = ggml_get_op_params_f32(weights, 1);
  9095. } else {
  9096. pc.output_scale = 1.0f;
  9097. pc.output_bias = 0.0f;
  9098. }
  9099. GGML_ASSERT(n_expert_used <= n_experts);
  9100. const uint32_t rows_per_block = 4;
  9101. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  9102. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, bias_buf, weights_buf, ids_buf}, pc, elements);
  9103. }
  9104. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  9105. ggml_tensor * dst = cgraph->nodes[node_idx];
  9106. const ggml_tensor * src0 = dst->src[0];
  9107. const ggml_tensor * src1 = dst->src[1];
  9108. const ggml_tensor * src2 = dst->src[2];
  9109. const ggml_tensor * src3 = nullptr;
  9110. const int n_dims = ((int32_t *) dst->op_params)[1];
  9111. const int mode = ((int32_t *) dst->op_params)[2];
  9112. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  9113. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  9114. const float freq_base = ((float *) dst->op_params)[5];
  9115. const float beta_fast = ((float *) dst->op_params)[9];
  9116. const float beta_slow = ((float *) dst->op_params)[10];
  9117. int sections[4] {};
  9118. if (mode & GGML_ROPE_TYPE_MROPE) {
  9119. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  9120. }
  9121. float corr_dims[2];
  9122. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  9123. uint32_t set_rows_stride = 0;
  9124. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  9125. // and overrides the dst and sets src3=row_indices
  9126. if (ctx->num_additional_fused_ops > 0) {
  9127. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  9128. src3 = cgraph->nodes[node_idx + 2]->src[1];
  9129. dst = cgraph->nodes[node_idx + 2];
  9130. }
  9131. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  9132. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  9133. }
  9134. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9135. const uint32_t * op_params = (const uint32_t *)dst->op_params;
  9136. uint32_t ncols = src0->ne[0];
  9137. uint32_t nrows = ggml_nrows(src0);
  9138. uint32_t ncols_pad_log2 = (uint32_t)ceilf(log2f(float(ncols)));
  9139. uint32_t ncolsp2 = 1 << ncols_pad_log2;
  9140. vk_op_argsort_push_constants pc { ncols, ncolsp2, ncols_pad_log2, nrows, op_params[0], 0, 0, 0, 0, };
  9141. // Pick the largest workgroup size <= ncolsp2
  9142. uint32_t pipeline_idx = std::min(ncols_pad_log2, num_argsort_pipelines - 1);
  9143. // Use the "small" argsort shader if the whole sort can be done by a single workgroup.
  9144. bool use_small = ncols_pad_log2 <= ctx->device->max_workgroup_size_log2 &&
  9145. ctx->device->pipeline_argsort_f32[pipeline_idx] != nullptr;
  9146. vk_pipeline pipeline = use_small ? ctx->device->pipeline_argsort_f32[pipeline_idx]
  9147. : ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  9148. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9149. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9150. vk_subbuffer subbuf1 = dst_buf;
  9151. // Reserve space for ivec2 per element, with rows padded to a power of two
  9152. if (!use_small) {
  9153. const size_t x_sz = size_t{ncolsp2} * nrows * 2 * sizeof(int);
  9154. if (ctx->prealloc_size_x < x_sz) {
  9155. ctx->prealloc_size_x = x_sz;
  9156. ggml_vk_preallocate_buffers(ctx, subctx);
  9157. }
  9158. if (ctx->prealloc_x_need_sync) {
  9159. ggml_vk_sync_buffers(ctx, subctx);
  9160. }
  9161. subbuf1 = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  9162. }
  9163. std::array<uint32_t, 3> elements;
  9164. elements[0] = ncolsp2;
  9165. elements[1] = std::min((uint32_t)ggml_nrows(src0), ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  9166. elements[2] = 1;
  9167. // First dispatch initializes tmp_idx and does the first N passes where
  9168. // there is only communication between threads in the same workgroup.
  9169. {
  9170. vk_op_argsort_push_constants pc2 = pc;
  9171. pc2.outer_start = 0;
  9172. pc2.outer_end = std::min(ncols_pad_log2, ctx->device->max_workgroup_size_log2);
  9173. pc2.inner_start = 0;
  9174. pc2.inner_end = 100;
  9175. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9176. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  9177. }
  9178. if (!use_small) {
  9179. ggml_vk_sync_buffers(ctx, subctx);
  9180. // Loop over outer/inner passes, synchronizing between each pass.
  9181. for (uint32_t outer = ctx->device->max_workgroup_size_log2; outer < ncols_pad_log2; ++outer) {
  9182. for (uint32_t inner = 0; inner < outer + 1; ++inner) {
  9183. vk_op_argsort_push_constants pc2 = pc;
  9184. pc2.outer_start = outer;
  9185. pc2.outer_end = outer + 1;
  9186. pc2.inner_start = inner;
  9187. pc2.inner_end = inner + 1;
  9188. // When the inner idx is large enough, there's only communication
  9189. // within a workgroup. So the remaining inner iterations can all
  9190. // run in the same dispatch.
  9191. if (outer - inner < pipeline_idx) {
  9192. pc2.inner_end = 100;
  9193. inner = outer;
  9194. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  9195. } else {
  9196. // Smaller workgroup empirically seems to perform better
  9197. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx - 2];
  9198. }
  9199. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9200. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  9201. ggml_vk_sync_buffers(ctx, subctx);
  9202. }
  9203. }
  9204. ctx->prealloc_x_need_sync = true;
  9205. }
  9206. }
  9207. static void ggml_vk_topk(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9208. uint32_t ncols = src0->ne[0];
  9209. uint32_t nrows = ggml_nrows(src0);
  9210. uint32_t k = dst->ne[0];
  9211. vk_op_topk_push_constants pc { ncols, ncols, ncols, k, nrows, 0, 0 };
  9212. if (ctx->prealloc_x_need_sync) {
  9213. ggml_vk_sync_buffers(ctx, subctx);
  9214. }
  9215. std::array<uint32_t, 3> elements;
  9216. elements[1] = std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  9217. elements[2] = 1;
  9218. uint32_t num_elements = ncols;
  9219. // Each iteration reduces a workgroup's worth of elements down to the K
  9220. // largest elements. Repeat until we have the top K elements.
  9221. // Need to do at least one iteration to write out the results.
  9222. bool done_one_iter = false;
  9223. uint32_t dbl_buf_index = 0;
  9224. size_t dbl_buf_size;
  9225. while (num_elements > k || !done_one_iter) {
  9226. // Prefer going as small as num_topk_pipelines - 3 for perf reasons.
  9227. // But if K is larger, then we need a larger workgroup
  9228. uint32_t max_pipeline = num_topk_pipelines - 1;
  9229. uint32_t preferred_pipeline = std::max(num_topk_pipelines - 3, (uint32_t)log2f(float(k)) + 2);
  9230. max_pipeline = std::min(preferred_pipeline, max_pipeline);
  9231. uint32_t min_pipeline = (uint32_t)log2f(float(k)) + 1;
  9232. // require full subgroup
  9233. min_pipeline = std::max(min_pipeline, ctx->device->subgroup_size_log2);
  9234. uint32_t pipeline_idx = (uint32_t)ceilf(log2f(float(num_elements)));
  9235. pipeline_idx = std::min(pipeline_idx, max_pipeline);
  9236. pipeline_idx = std::max(pipeline_idx, min_pipeline);
  9237. if (num_elements > (1u << pipeline_idx)) {
  9238. // If we could finish on this loop iteration (i.e. a single workgroup)
  9239. // then do so. It's better than the overhead of another pass.
  9240. for (uint32_t i = pipeline_idx; i < num_topk_pipelines; ++i) {
  9241. if (num_elements <= (1u << i)) {
  9242. pipeline_idx = i;
  9243. break;
  9244. }
  9245. }
  9246. }
  9247. vk_pipeline pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  9248. // If the device doesn't support a pipeline this large, use smaller
  9249. while (!pipeline) {
  9250. pipeline_idx--;
  9251. GGML_ASSERT(pipeline_idx >= min_pipeline);
  9252. pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  9253. }
  9254. vk_op_topk_push_constants pc2 = pc;
  9255. pc2.ncols_input = num_elements;
  9256. // Number of elements remaining after this pass
  9257. uint32_t num_dst_elements = (num_elements / pipeline->wg_denoms[0]) * k + std::min(k, num_elements % pipeline->wg_denoms[0]);
  9258. pc2.ncols_output = num_dst_elements;
  9259. if (!done_one_iter) {
  9260. // Reserve space for ivec2 per element, double buffered
  9261. // K per workgroup per row
  9262. dbl_buf_size = num_dst_elements * nrows * 2 * sizeof(int);
  9263. dbl_buf_size = ROUNDUP_POW2(dbl_buf_size, ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  9264. const size_t x_sz = dbl_buf_size * 2;
  9265. if (ctx->prealloc_size_x < x_sz) {
  9266. ctx->prealloc_size_x = x_sz;
  9267. ggml_vk_preallocate_buffers(ctx, subctx);
  9268. }
  9269. }
  9270. vk_subbuffer src_buf;
  9271. vk_subbuffer dst_buf;
  9272. if (num_elements == ncols) {
  9273. pc2.first_pass = 1;
  9274. src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9275. } else {
  9276. src_buf = { ctx->prealloc_x, dbl_buf_index * dbl_buf_size, dbl_buf_size };
  9277. }
  9278. if (num_dst_elements == k) {
  9279. pc2.last_pass = 1;
  9280. dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9281. } else {
  9282. dst_buf = { ctx->prealloc_x, (dbl_buf_index ^ 1) * dbl_buf_size, dbl_buf_size };
  9283. }
  9284. elements[0] = num_elements;
  9285. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9286. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src_buf, dst_buf }, pc2, elements);
  9287. num_elements = num_dst_elements;
  9288. dbl_buf_index ^= 1;
  9289. if (num_elements > k) {
  9290. ggml_vk_sync_buffers(ctx, subctx);
  9291. }
  9292. done_one_iter = true;
  9293. }
  9294. ctx->prealloc_x_need_sync = true;
  9295. }
  9296. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9297. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  9298. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  9299. }
  9300. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9301. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9302. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  9303. }
  9304. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9305. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9306. p.weight = 1.0f / (float)src0->ne[0];
  9307. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  9308. }
  9309. static void ggml_vk_cumsum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9310. vk_op_sum_rows_push_constants pc = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9311. // Use the single pass shader when the rows are small or there are enough rows to fill the GPU.
  9312. // For fewer, larger rows, use the multipass shader to spread each row across SMs.
  9313. if (dst->ne[0] <= 4096 || ggml_nrows(dst) >= ctx->device->shader_core_count) {
  9314. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CUMSUM, pc);
  9315. return;
  9316. }
  9317. // First pass computes partial sums within a block, and stores the last partial
  9318. // to the temp buffer. Second pass sums the block partials from the temp buffer
  9319. // and adds that to the result of the first pass.
  9320. vk_pipeline pipeline1 = ctx->device->pipeline_cumsum_multipass1_f32;
  9321. vk_pipeline pipeline2 = ctx->device->pipeline_cumsum_multipass2_f32;
  9322. GGML_ASSERT(pipeline1 != nullptr && pipeline2 != nullptr);
  9323. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  9324. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  9325. std::array<uint32_t, 3> elements;
  9326. elements[0] = dst->ne[0];
  9327. elements[1] = (uint32_t)ggml_nrows(dst);
  9328. elements[2] = 1;
  9329. size_t temp_size = sizeof(float) * elements[0] * ggml_nrows(dst);
  9330. if (ctx->prealloc_size_split_k < temp_size) {
  9331. ctx->prealloc_size_split_k = temp_size;
  9332. ggml_vk_preallocate_buffers(ctx, subctx);
  9333. }
  9334. vk_subbuffer src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9335. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9336. vk_subbuffer temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  9337. if (ctx->prealloc_split_k_need_sync) {
  9338. ggml_vk_sync_buffers(ctx, subctx);
  9339. }
  9340. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, {src_buf, dst_buf, temp_buf}, pc, elements);
  9341. ggml_vk_sync_buffers(ctx, subctx);
  9342. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, {src_buf, dst_buf, temp_buf}, pc, elements);
  9343. ctx->prealloc_split_k_need_sync = true;
  9344. }
  9345. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9346. 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, 0.0f, 0.0f });
  9347. }
  9348. 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) {
  9349. 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, 0.0f, 0.0f });
  9350. }
  9351. 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) {
  9352. const uint32_t src0_type_size = ggml_type_size(src0->type);
  9353. const uint32_t src1_type_size = ggml_type_size(src1->type);
  9354. const uint32_t dst_type_size = ggml_type_size(dst->type);
  9355. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOLVE_TRI, {
  9356. (uint32_t)ggml_nelements(src0),
  9357. (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,
  9358. (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,
  9359. (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,
  9360. 0,
  9361. 0.0f, 0.0f, 0,
  9362. });
  9363. }
  9364. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9365. const int32_t s0 = dst->op_params[0];
  9366. const int32_t s1 = dst->op_params[1];
  9367. const int32_t p0 = dst->op_params[2];
  9368. const int32_t p1 = dst->op_params[3];
  9369. const int32_t d0 = dst->op_params[4];
  9370. const int32_t d1 = dst->op_params[5];
  9371. const bool is_2D = dst->op_params[6] == 1;
  9372. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  9373. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  9374. const uint32_t IW = src1->ne[0];
  9375. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  9376. const uint32_t KW = src0->ne[0];
  9377. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  9378. const uint32_t OW = dst->ne[1];
  9379. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  9380. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  9381. const uint32_t pelements = OW * KW * KH;
  9382. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  9383. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9384. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9385. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9386. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  9387. dst_addr,
  9388. batch_offset, offset_delta,
  9389. IC, IW, IH, OW, OH, KW, KH,
  9390. pelements,
  9391. IC * KH * KW,
  9392. s0, s1, p0, p1, d0, d1, batch * IC
  9393. });
  9394. }
  9395. 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) {
  9396. GGML_TENSOR_BINARY_OP_LOCALS
  9397. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  9398. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  9399. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  9400. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  9401. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  9402. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  9403. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  9404. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  9405. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  9406. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  9407. const int64_t N = ne13 / IC;
  9408. const int64_t ID = ne12;
  9409. const int64_t IH = ne11;
  9410. const int64_t IW = ne10;
  9411. const int64_t KD = ne02;
  9412. const int64_t KH = ne01;
  9413. const int64_t KW = ne00;
  9414. const int64_t OD = ne3 / N;
  9415. const int64_t OH = ne2;
  9416. const int64_t OW = ne1;
  9417. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9418. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9419. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9420. vk_op_im2col_3d_push_constants pc {};
  9421. pc.dst_addr = dst_addr;
  9422. pc.nb10 = nb10 / ggml_type_size(src1->type);
  9423. pc.nb11 = nb11 / ggml_type_size(src1->type);
  9424. pc.nb12 = nb12 / ggml_type_size(src1->type);
  9425. pc.nb13 = nb13 / ggml_type_size(src1->type);
  9426. pc.s0 = s0;
  9427. pc.s1 = s1;
  9428. pc.s2 = s2;
  9429. pc.p0 = p0;
  9430. pc.p1 = p1;
  9431. pc.p2 = p2;
  9432. pc.d0 = d0;
  9433. pc.d1 = d1;
  9434. pc.d2 = d2;
  9435. pc.IW = IW;
  9436. pc.IH = IH;
  9437. pc.ID = ID;
  9438. pc.IC = IC;
  9439. pc.KW = KW;
  9440. pc.OH = OH;
  9441. pc.KD_KH_KW = KD*KH*KW;
  9442. pc.KH_KW = KH*KW;
  9443. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  9444. pc.N_OD_OH = N*OD*OH;
  9445. pc.OD_OH = OD*OH;
  9446. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  9447. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  9448. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  9449. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  9450. }
  9451. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9452. const uint32_t dim = dst->op_params[0];
  9453. const uint32_t max_period = dst->op_params[1];
  9454. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  9455. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  9456. nb1, dim, max_period,
  9457. });
  9458. }
  9459. 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) {
  9460. // src0: (K, Cout, Cin, 1) -- kernel
  9461. // src1: (L, Cin, 1, 1) -- input
  9462. // dst: (*, Cout, 1, 1)
  9463. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  9464. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9465. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  9466. GGML_TENSOR_BINARY_OP_LOCALS
  9467. GGML_ASSERT(nb00 == sizeof(float));
  9468. GGML_ASSERT(nb10 == sizeof(float));
  9469. const int32_t s0 = dst->op_params[0];
  9470. vk_op_conv_transpose_1d_push_constants p{};
  9471. p.Cout = static_cast<uint32_t>(ne01);
  9472. p.Cin = static_cast<uint32_t>(ne02);
  9473. p.K = static_cast<uint32_t>(ne00);
  9474. p.L = static_cast<uint32_t>(ne10);
  9475. p.KL = static_cast<uint32_t>(ne0);
  9476. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9477. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9478. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9479. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9480. p.s0 = static_cast<uint32_t>(s0);
  9481. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  9482. }
  9483. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9484. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  9485. const int32_t k1 = dst->op_params[1];
  9486. const int32_t k0 = dst->op_params[2];
  9487. const int32_t s1 = dst->op_params[3];
  9488. const int32_t s0 = dst->op_params[4];
  9489. const int32_t p1 = dst->op_params[5];
  9490. const int32_t p0 = dst->op_params[6];
  9491. const uint32_t IH = src0->ne[1];
  9492. const uint32_t IW = src0->ne[0];
  9493. const uint32_t N = dst->ne[3];
  9494. const uint32_t OC = dst->ne[2];
  9495. const uint32_t OH = dst->ne[1];
  9496. const uint32_t OW = dst->ne[0];
  9497. const uint32_t parallel_elements = N * OC * OH * OW;
  9498. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  9499. IW, IH, OW, OH, OC,
  9500. parallel_elements,
  9501. op,
  9502. k0, k1, s0, s1, p0, p1,
  9503. });
  9504. }
  9505. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  9506. const ggml_tensor * src1, ggml_tensor * dst) {
  9507. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  9508. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9509. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  9510. GGML_TENSOR_BINARY_OP_LOCALS
  9511. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  9512. GGML_ASSERT(nb10 == sizeof(float));
  9513. GGML_ASSERT(nb0 == sizeof(float));
  9514. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  9515. vk_op_conv2d_push_constants p{};
  9516. p.Cout = static_cast<uint32_t>(!transpose ? ne03 : ne02);
  9517. p.Cin = static_cast<uint32_t>(!transpose ? ne02 : ne03);
  9518. p.N = static_cast<uint32_t>(ne13);
  9519. GGML_ASSERT(p.Cout == ne2);
  9520. GGML_ASSERT(p.Cin == ne12);
  9521. p.W = static_cast<uint32_t>(ne10);
  9522. p.H = static_cast<uint32_t>(ne11);
  9523. p.OW = static_cast<uint32_t>(ne0);
  9524. p.OH = static_cast<uint32_t>(ne1);
  9525. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9526. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9527. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  9528. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9529. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  9530. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  9531. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9532. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  9533. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  9534. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, dst->op, std::move(p));
  9535. }
  9536. 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) {
  9537. vk_op_conv2d_dw_push_constants p{};
  9538. p.ne = ggml_nelements(dst);
  9539. p.channels = dst->ne[2];
  9540. p.batches = dst->ne[3];
  9541. p.dst_w = dst->ne[0];
  9542. p.dst_h = dst->ne[1];
  9543. p.src_w = src1->ne[0];
  9544. p.src_h = src1->ne[1];
  9545. p.knl_w = src0->ne[0];
  9546. p.knl_h = src0->ne[1];
  9547. p.stride_x = dst->op_params[0];
  9548. p.stride_y = dst->op_params[1];
  9549. p.pad_x = dst->op_params[2];
  9550. p.pad_y = dst->op_params[3];
  9551. p.dilation_x = dst->op_params[4];
  9552. p.dilation_y = dst->op_params[5];
  9553. GGML_ASSERT(src0->ne[3] == p.channels);
  9554. GGML_ASSERT(src1->ne[3] == p.batches);
  9555. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  9556. }
  9557. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9558. const float * op_params = (const float *)dst->op_params;
  9559. 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, 0.0f, 0.0f });
  9560. }
  9561. #ifdef GGML_VULKAN_RUN_TESTS
  9562. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  9563. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  9564. return;
  9565. }
  9566. i0 = std::max(i0, 5);
  9567. i1 = std::max(i1, 5);
  9568. i2 = std::max(i2, 0);
  9569. fprintf(stderr, " ");
  9570. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9571. fprintf(stderr, "%7d ", idx1);
  9572. }
  9573. fprintf(stderr, "\n");
  9574. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9575. fprintf(stderr, "%7d: ", idx0);
  9576. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9577. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  9578. float val;
  9579. if (type == GGML_TYPE_F32) {
  9580. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  9581. } else if (type == GGML_TYPE_F16) {
  9582. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  9583. } else {
  9584. GGML_ABORT("fatal error");
  9585. }
  9586. fprintf(stderr, "% 7.2f ", val);
  9587. } else {
  9588. fprintf(stderr, " ");
  9589. }
  9590. }
  9591. fprintf(stderr, "\n");
  9592. }
  9593. }
  9594. template <typename X_TYPE, typename Y_TYPE>
  9595. 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) {
  9596. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  9597. const size_t x_ne = m * k * batch;
  9598. const size_t y_ne = k * n * batch;
  9599. const size_t d_ne = m * n * batch;
  9600. vk_pipeline p;
  9601. std::string shname;
  9602. if (shader_size == 0) {
  9603. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9604. p = ctx->device->pipeline_matmul_f32->a_s;
  9605. shname = "F32_ALIGNED_S";
  9606. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9607. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  9608. shname = "F32_F16_ALIGNED_S";
  9609. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9610. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  9611. shname = "F16_F32_ALIGNED_S";
  9612. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9613. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  9614. shname = "F16_ALIGNED_S";
  9615. } else {
  9616. GGML_ABORT("fatal error");
  9617. }
  9618. } else if (shader_size == 1) {
  9619. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9620. p = ctx->device->pipeline_matmul_f32->a_m;
  9621. shname = "F32_ALIGNED_M";
  9622. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9623. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  9624. shname = "F32_F16_ALIGNED_M";
  9625. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9626. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  9627. shname = "F16_F32_ALIGNED_M";
  9628. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9629. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  9630. shname = "F16_ALIGNED_M";
  9631. } else {
  9632. GGML_ABORT("fatal error");
  9633. }
  9634. } else if (shader_size == 2) {
  9635. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9636. p = ctx->device->pipeline_matmul_f32->a_l;
  9637. shname = "F32_ALIGNED_L";
  9638. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9639. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  9640. shname = "F32_F16_ALIGNED_L";
  9641. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9642. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  9643. shname = "F16_F32_ALIGNED_L";
  9644. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9645. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  9646. shname = "F16_ALIGNED_L";
  9647. } else {
  9648. GGML_ABORT("fatal error");
  9649. }
  9650. } else {
  9651. GGML_ASSERT(0);
  9652. }
  9653. const size_t kpad = ggml_vk_align_size(k, p->align);
  9654. if (k != kpad) {
  9655. if (shader_size == 0) {
  9656. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9657. p = ctx->device->pipeline_matmul_f32->s;
  9658. shname = "F32_S";
  9659. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9660. p = ctx->device->pipeline_matmul_f32_f16->s;
  9661. shname = "F32_F16_S";
  9662. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9663. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  9664. shname = "F16_F32_S";
  9665. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9666. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  9667. shname = "F16_S";
  9668. }
  9669. } else if (shader_size == 1) {
  9670. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9671. p = ctx->device->pipeline_matmul_f32->m;
  9672. shname = "F32_M";
  9673. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9674. p = ctx->device->pipeline_matmul_f32_f16->m;
  9675. shname = "F32_F16_M";
  9676. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9677. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  9678. shname = "F16_F32_M";
  9679. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9680. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  9681. shname = "F16_M";
  9682. }
  9683. } else if (shader_size == 2) {
  9684. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9685. p = ctx->device->pipeline_matmul_f32->l;
  9686. shname = "F32_L";
  9687. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9688. p = ctx->device->pipeline_matmul_f32_f16->l;
  9689. shname = "F32_F16_L";
  9690. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9691. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  9692. shname = "F16_F32_L";
  9693. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9694. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  9695. shname = "F16_L";
  9696. }
  9697. }
  9698. }
  9699. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9700. if (split_k > 1) {
  9701. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9702. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9703. // Resize buffer
  9704. if (ctx->prealloc_split_k != nullptr) {
  9705. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9706. }
  9707. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9708. }
  9709. }
  9710. ggml_pipeline_allocate_descriptor_sets(ctx);
  9711. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9712. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9713. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9714. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9715. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9716. float* d = (float *) malloc(sizeof(float) * d_ne);
  9717. for (size_t i = 0; i < x_ne; i++) {
  9718. if (std::is_same<float, X_TYPE>()) {
  9719. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9720. // x[i] = 1.0f;
  9721. // x[i] = i + 1;
  9722. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9723. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9724. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9725. // x[i] = ggml_fp32_to_fp16(1.0f);
  9726. // x[i] = ggml_fp32_to_fp16(i + 1);
  9727. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9728. } else {
  9729. GGML_ABORT("fatal error");
  9730. }
  9731. }
  9732. for (size_t i = 0; i < y_ne; i++) {
  9733. if (std::is_same<float, Y_TYPE>()) {
  9734. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9735. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9736. // y[i] = i + 1;
  9737. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9738. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9739. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9740. // y[i] = ggml_fp32_to_fp16(i + 1);
  9741. } else {
  9742. GGML_ABORT("fatal error");
  9743. }
  9744. }
  9745. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9746. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9747. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9748. ggml_vk_ctx_begin(ctx->device, subctx);
  9749. for (size_t i = 0; i < num_it; i++) {
  9750. ggml_vk_matmul(
  9751. 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),
  9752. m, n, k,
  9753. k, k, m, k*m, k*n, m*n,
  9754. split_k, batch, batch, batch, 1, 1, n
  9755. );
  9756. }
  9757. ggml_vk_ctx_end(subctx);
  9758. auto begin = std::chrono::high_resolution_clock::now();
  9759. ggml_vk_submit(subctx, ctx->fence);
  9760. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9761. ctx->device->device.resetFences({ ctx->fence });
  9762. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9763. auto end = std::chrono::high_resolution_clock::now();
  9764. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9765. // copy dst to host
  9766. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9767. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9768. ggml_init_params iparams = {
  9769. /*.mem_size =*/ 1024*1024*1024,
  9770. /*.mem_buffer =*/ NULL,
  9771. /*.no_alloc =*/ true,
  9772. };
  9773. ggml_context * ggml_ctx = ggml_init(iparams);
  9774. ggml_type src0_type;
  9775. ggml_type src1_type;
  9776. if (std::is_same<float, X_TYPE>()) {
  9777. src0_type = GGML_TYPE_F32;
  9778. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9779. src0_type = GGML_TYPE_F16;
  9780. } else {
  9781. GGML_ABORT("fatal error");
  9782. }
  9783. if (std::is_same<float, Y_TYPE>()) {
  9784. src1_type = GGML_TYPE_F32;
  9785. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9786. src1_type = GGML_TYPE_F16;
  9787. } else {
  9788. GGML_ABORT("fatal error");
  9789. }
  9790. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9791. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9792. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9793. src0_ggml->data = x;
  9794. src1_ggml->data = y;
  9795. tensor_ggml->data = d_chk;
  9796. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9797. ggml_build_forward_expand(cgraph, tensor_ggml);
  9798. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9799. ggml_free(ggml_ctx);
  9800. double avg_err = 0.0;
  9801. int first_err_n = -1;
  9802. int first_err_m = -1;
  9803. int first_err_b = -1;
  9804. for (size_t i = 0; i < m*n*batch; i++) {
  9805. double err = std::fabs(d[i] - d_chk[i]);
  9806. avg_err += err;
  9807. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9808. first_err_b = i / (m * n);
  9809. first_err_n = (i % (m * n)) / m;
  9810. first_err_m = (i % (m * n)) % m;
  9811. }
  9812. }
  9813. avg_err /= m * n;
  9814. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9815. 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;
  9816. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9817. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9818. std::cerr << "Actual result: " << std::endl << std::endl;
  9819. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9820. std::cerr << "Expected result: " << std::endl << std::endl;
  9821. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9822. if (split_k > 1) {
  9823. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9824. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9825. std::cerr << "d_buf0: " << std::endl << std::endl;
  9826. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9827. std::cerr << "d_buf1: " << std::endl << std::endl;
  9828. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9829. std::cerr << "d_buf2: " << std::endl << std::endl;
  9830. 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);
  9831. std::cerr << "d_buf3: " << std::endl << std::endl;
  9832. 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);
  9833. free(split_k_buf);
  9834. }
  9835. }
  9836. free(d_chk);
  9837. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9838. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9839. ggml_vk_destroy_buffer(d_X);
  9840. ggml_vk_destroy_buffer(d_Y);
  9841. ggml_vk_destroy_buffer(d_D);
  9842. free(x);
  9843. free(y);
  9844. free(d);
  9845. }
  9846. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9847. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9848. return;
  9849. }
  9850. i0 = std::max(i0, 5);
  9851. i1 = std::max(i1, 5);
  9852. i2 = std::max(i2, 0);
  9853. i3 = std::max(i3, 0);
  9854. fprintf(stderr, " ");
  9855. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9856. fprintf(stderr, "%7d ", idx1);
  9857. }
  9858. fprintf(stderr, "\n");
  9859. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9860. fprintf(stderr, "%7d: ", idx0);
  9861. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9862. 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]) {
  9863. float val;
  9864. if (tensor->type == GGML_TYPE_F32) {
  9865. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9866. } else if (tensor->type == GGML_TYPE_F16) {
  9867. 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]));
  9868. } else {
  9869. GGML_ABORT("fatal error");
  9870. }
  9871. fprintf(stderr, "% 7.2f ", val);
  9872. } else {
  9873. fprintf(stderr, " ");
  9874. }
  9875. }
  9876. fprintf(stderr, "\n");
  9877. }
  9878. }
  9879. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9880. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9881. }
  9882. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9883. if (quant == GGML_TYPE_F32) {
  9884. memcpy(to, from, sizeof(float) * ne);
  9885. return;
  9886. }
  9887. const auto * tt = ggml_get_type_traits(quant);
  9888. ggml_to_float_t dequant_fn = tt->to_float;
  9889. dequant_fn(from, to, ne);
  9890. }
  9891. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9892. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9893. const size_t x_sz = sizeof(float) * ne;
  9894. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9895. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9896. float * x = (float *) malloc(x_sz);
  9897. void * qx = malloc(qx_sz);
  9898. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9899. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9900. float * x_ref = (float *) malloc(x_sz);
  9901. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9902. for (size_t i = 0; i < ne; i++) {
  9903. x[i] = rand() / (float)RAND_MAX;
  9904. }
  9905. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9906. ggml_vk_quantize_data(x, qx, ne, quant);
  9907. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9908. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9909. ggml_pipeline_allocate_descriptor_sets(ctx);
  9910. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9911. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9912. ggml_vk_ctx_begin(ctx->device, subctx);
  9913. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9914. 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});
  9915. ggml_vk_ctx_end(subctx);
  9916. auto begin = std::chrono::high_resolution_clock::now();
  9917. ggml_vk_submit(subctx, ctx->fence);
  9918. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9919. ctx->device->device.resetFences({ ctx->fence });
  9920. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9921. auto end = std::chrono::high_resolution_clock::now();
  9922. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9923. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9924. int first_err = -1;
  9925. double avg_err = 0.0;
  9926. for (size_t i = 0; i < ne; i++) {
  9927. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9928. avg_err += error;
  9929. if (first_err < 0 && error > 0.05) {
  9930. first_err = i;
  9931. }
  9932. }
  9933. avg_err /= ne;
  9934. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9935. if (avg_err > 0.1) {
  9936. std::cerr << "first_error = " << first_err << std::endl;
  9937. std::cerr << "Actual result: " << std::endl << std::endl;
  9938. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9939. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9940. }
  9941. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9942. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9943. std::cerr << x_ref[i] << ", ";
  9944. }
  9945. std::cerr << std::endl;
  9946. }
  9947. ggml_vk_destroy_buffer(x_buf);
  9948. ggml_vk_destroy_buffer(qx_buf);
  9949. free(x);
  9950. free(qx);
  9951. free(x_ref);
  9952. free(x_chk);
  9953. }
  9954. // This does not work without ggml q8_1 quantization support
  9955. //
  9956. // typedef uint16_t ggml_half;
  9957. // typedef uint32_t ggml_half2;
  9958. //
  9959. // #define QK8_1 32
  9960. // typedef struct {
  9961. // union {
  9962. // struct {
  9963. // ggml_half d; // delta
  9964. // ggml_half s; // d * sum(qs[i])
  9965. // } GGML_COMMON_AGGR_S;
  9966. // ggml_half2 ds;
  9967. // } GGML_COMMON_AGGR_U;
  9968. // int8_t qs[QK8_1]; // quants
  9969. // } block_q8_1;
  9970. //
  9971. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9972. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9973. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9974. //
  9975. // const size_t x_sz = sizeof(float) * ne;
  9976. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9977. // float * x = (float *) malloc(x_sz);
  9978. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9979. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9980. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9981. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9982. //
  9983. // for (size_t i = 0; i < ne; i++) {
  9984. // x[i] = rand() / (float)RAND_MAX;
  9985. // }
  9986. //
  9987. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9988. //
  9989. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9990. //
  9991. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9992. //
  9993. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9994. //
  9995. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9996. // ggml_vk_ctx_begin(ctx->device, subctx);
  9997. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9998. // ggml_vk_ctx_end(subctx);
  9999. //
  10000. // auto begin = std::chrono::high_resolution_clock::now();
  10001. //
  10002. // ggml_vk_submit(subctx, ctx->fence);
  10003. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  10004. // ctx->device->device.resetFences({ ctx->fence });
  10005. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  10006. //
  10007. // auto end = std::chrono::high_resolution_clock::now();
  10008. //
  10009. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  10010. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  10011. //
  10012. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  10013. //
  10014. // int first_err = -1;
  10015. //
  10016. // for (size_t i = 0; i < ne / 32; i++) {
  10017. // 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));
  10018. //
  10019. // if (first_err < 0 && error > 0.1) {
  10020. // first_err = i;
  10021. // }
  10022. //
  10023. // 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));
  10024. //
  10025. // if (first_err < 0 && error > 0.1) {
  10026. // first_err = i;
  10027. // }
  10028. //
  10029. // for (size_t j = 0; j < 32; j++) {
  10030. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  10031. //
  10032. // if (first_err < 0 && error > 1) {
  10033. // first_err = i;
  10034. // }
  10035. // }
  10036. // }
  10037. //
  10038. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  10039. //
  10040. // if (first_err != -1) {
  10041. // std::cerr << "first_error = " << first_err << std::endl;
  10042. // std::cerr << "Actual result: " << std::endl << std::endl;
  10043. // 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) << " ";
  10044. // for (size_t j = 0; j < 32; j++) {
  10045. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  10046. // }
  10047. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  10048. // 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) << " ";
  10049. // for (size_t j = 0; j < 32; j++) {
  10050. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  10051. // }
  10052. // std::cerr << std::endl;
  10053. // }
  10054. //
  10055. // ggml_vk_destroy_buffer(x_buf);
  10056. // ggml_vk_destroy_buffer(qx_buf);
  10057. //
  10058. // free(x);
  10059. // free(qx);
  10060. // free(qx_res);
  10061. // }
  10062. 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) {
  10063. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  10064. const size_t x_ne = m * k * batch;
  10065. const size_t y_ne = k * n * batch;
  10066. const size_t d_ne = m * n * batch;
  10067. vk_matmul_pipeline2 * pipelines;
  10068. if (mmq) {
  10069. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  10070. } else {
  10071. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  10072. }
  10073. const bool fp16acc = ctx->device->fp16;
  10074. vk_pipeline p;
  10075. std::string shname;
  10076. if (shader_size == 0) {
  10077. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  10078. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  10079. } else if (shader_size == 1) {
  10080. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  10081. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  10082. } else if (shader_size == 2) {
  10083. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  10084. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  10085. } else {
  10086. GGML_ASSERT(0);
  10087. }
  10088. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  10089. if (mmq || k != kpad) {
  10090. if (shader_size == 0) {
  10091. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  10092. shname = std::string(ggml_type_name(quant)) + "_S";
  10093. } else if (shader_size == 1) {
  10094. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  10095. shname = std::string(ggml_type_name(quant)) + "_M";
  10096. } else if (shader_size == 2) {
  10097. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  10098. shname = std::string(ggml_type_name(quant)) + "_L";
  10099. } else {
  10100. GGML_ASSERT(0);
  10101. }
  10102. }
  10103. if (p == nullptr) {
  10104. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  10105. return;
  10106. }
  10107. const size_t x_sz = sizeof(float) * x_ne;
  10108. const size_t y_sz = sizeof(float) * y_ne;
  10109. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  10110. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  10111. const size_t d_sz = sizeof(float) * d_ne;
  10112. float * x = (float *) malloc(x_sz);
  10113. float * y = (float *) malloc(y_sz);
  10114. void * qx = malloc(qx_sz);
  10115. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10116. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10117. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10118. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10119. float * d = (float *) malloc(d_sz);
  10120. float * d_chk = (float *) malloc(d_sz);
  10121. for (size_t i = 0; i < x_ne; i++) {
  10122. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  10123. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  10124. // x[i] = i % k;
  10125. }
  10126. ggml_vk_quantize_data(x, qx, x_ne, quant);
  10127. for (size_t i = 0; i < y_ne; i++) {
  10128. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  10129. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  10130. // y[i] = i % k;
  10131. }
  10132. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  10133. if (split_k > 1) {
  10134. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  10135. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  10136. // Resize buffer
  10137. if (ctx->prealloc_split_k != nullptr) {
  10138. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10139. }
  10140. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10141. }
  10142. }
  10143. if (mmq) {
  10144. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  10145. }
  10146. ggml_pipeline_allocate_descriptor_sets(ctx);
  10147. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  10148. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  10149. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10150. ggml_vk_ctx_begin(ctx->device, subctx);
  10151. if (mmq) {
  10152. for (size_t i = 0; i < num_it; i++) {
  10153. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  10154. ggml_vk_matmul(
  10155. 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 },
  10156. m, n, k,
  10157. k, k, m, k*m, k*n, m*n,
  10158. split_k, batch, batch, batch, 1, 1, n
  10159. );
  10160. }
  10161. } else {
  10162. for (size_t i = 0; i < num_it; i++) {
  10163. ggml_vk_matmul(
  10164. 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 },
  10165. m, n, k,
  10166. k, k, m, k*m, k*n, m*n,
  10167. split_k, batch, batch, batch, 1, 1, n
  10168. );
  10169. }
  10170. }
  10171. ggml_vk_ctx_end(subctx);
  10172. auto begin = std::chrono::high_resolution_clock::now();
  10173. ggml_vk_submit(subctx, ctx->fence);
  10174. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  10175. ctx->device->device.resetFences({ ctx->fence });
  10176. ggml_vk_queue_command_pools_cleanup(ctx->device);
  10177. auto end = std::chrono::high_resolution_clock::now();
  10178. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  10179. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  10180. ggml_init_params iparams = {
  10181. /*.mem_size =*/ 1024*1024*1024,
  10182. /*.mem_buffer =*/ NULL,
  10183. /*.no_alloc =*/ true,
  10184. };
  10185. ggml_context * ggml_ctx = ggml_init(iparams);
  10186. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  10187. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  10188. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  10189. src0_ggml->data = qx;
  10190. src1_ggml->data = y;
  10191. tensor_ggml->data = d_chk;
  10192. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  10193. ggml_build_forward_expand(cgraph, tensor_ggml);
  10194. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  10195. ggml_free(ggml_ctx);
  10196. double avg_err = 0.0;
  10197. int first_err_n = -1;
  10198. int first_err_m = -1;
  10199. int first_err_b = -1;
  10200. for (size_t i = 0; i < m*n*batch; i++) {
  10201. double err = std::fabs(d[i] - d_chk[i]);
  10202. avg_err += err;
  10203. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  10204. first_err_b = i / (m * n);
  10205. first_err_n = (i % (m * n)) / m;
  10206. first_err_m = (i % (m * n)) % m;
  10207. }
  10208. }
  10209. avg_err /= m * n;
  10210. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  10211. std::cerr << "TEST dequant matmul " << shname;
  10212. if (mmq) {
  10213. std::cerr << " mmq";
  10214. }
  10215. 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;
  10216. if (avg_err > 0.01 || std::isnan(avg_err)) {
  10217. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  10218. std::cerr << "Actual result: " << std::endl << std::endl;
  10219. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10220. std::cerr << std::endl;
  10221. std::cerr << "Expected result: " << std::endl << std::endl;
  10222. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10223. std::cerr << "src0: " << std::endl << std::endl;
  10224. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  10225. std::cerr << std::endl;
  10226. std::cerr << "src1: " << std::endl << std::endl;
  10227. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  10228. if (split_k > 1) {
  10229. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  10230. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  10231. std::cerr << "d_buf0: " << std::endl << std::endl;
  10232. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10233. std::cerr << "d_buf1: " << std::endl << std::endl;
  10234. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10235. std::cerr << "d_buf2: " << std::endl << std::endl;
  10236. 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);
  10237. std::cerr << "d_buf3: " << std::endl << std::endl;
  10238. 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);
  10239. free(split_k_buf);
  10240. }
  10241. }
  10242. ggml_vk_destroy_buffer(qx_buf);
  10243. ggml_vk_destroy_buffer(y_buf);
  10244. ggml_vk_destroy_buffer(qy_buf);
  10245. ggml_vk_destroy_buffer(d_buf);
  10246. free(x);
  10247. free(qx);
  10248. free(y);
  10249. free(d);
  10250. free(d_chk);
  10251. }
  10252. #endif
  10253. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  10254. #if defined(GGML_VULKAN_RUN_TESTS)
  10255. const std::vector<size_t> vals {
  10256. 512, 512, 128,
  10257. 128, 512, 512,
  10258. 4096, 512, 4096,
  10259. 11008, 512, 4096,
  10260. 4096, 512, 11008,
  10261. 32000, 512, 4096,
  10262. 8, 8, 8,
  10263. 100, 46, 576,
  10264. 623, 111, 128,
  10265. 100, 46, 558,
  10266. 512, 1, 256,
  10267. 128, 110, 622,
  10268. 511, 511, 127,
  10269. 511, 511, 7,
  10270. 511, 511, 17,
  10271. 49, 49, 128,
  10272. 128, 49, 49,
  10273. 4096, 49, 4096,
  10274. };
  10275. const size_t num_it = 100;
  10276. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  10277. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  10278. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  10279. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  10280. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  10281. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  10282. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  10283. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  10284. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  10285. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  10286. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  10287. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  10288. abort();
  10289. for (size_t i = 0; i < vals.size(); i += 3) {
  10290. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  10291. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  10292. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  10293. std::cerr << '\n';
  10294. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  10295. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  10296. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  10297. std::cerr << '\n';
  10298. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  10299. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  10300. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  10301. std::cerr << '\n' << std::endl;
  10302. if (vals[i + 2] % 32 == 0) {
  10303. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  10304. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  10305. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  10306. std::cerr << '\n';
  10307. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  10308. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  10309. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  10310. std::cerr << '\n';
  10311. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  10312. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  10313. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  10314. std::cerr << '\n' << std::endl;
  10315. }
  10316. if (vals[i + 2] % 256 == 0) {
  10317. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  10318. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  10319. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  10320. std::cerr << '\n';
  10321. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  10322. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  10323. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  10324. std::cerr << '\n';
  10325. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  10326. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  10327. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  10328. std::cerr << '\n' << std::endl;
  10329. }
  10330. }
  10331. GGML_ABORT("fatal error");
  10332. #endif
  10333. if (subctx) {
  10334. // Submit and wait for any pending work before reallocating the buffers
  10335. ggml_vk_ctx_end(subctx);
  10336. ggml_vk_submit(subctx, {});
  10337. ctx->submit_pending = true;
  10338. ggml_vk_synchronize(ctx);
  10339. ggml_vk_ctx_begin(ctx->device, subctx);
  10340. }
  10341. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  10342. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  10343. // Resize buffer
  10344. if (ctx->prealloc_x != nullptr) {
  10345. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10346. }
  10347. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  10348. }
  10349. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  10350. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  10351. // Resize buffer
  10352. if (ctx->prealloc_y != nullptr) {
  10353. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10354. }
  10355. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  10356. }
  10357. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  10358. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  10359. // Resize buffer
  10360. if (ctx->prealloc_split_k != nullptr) {
  10361. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10362. }
  10363. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  10364. }
  10365. 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)) {
  10366. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  10367. // Resize buffer
  10368. if (ctx->prealloc_add_rms_partials != nullptr) {
  10369. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10370. }
  10371. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  10372. }
  10373. }
  10374. static void ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool almost_ready);
  10375. // Returns true if node has enqueued work into the queue, false otherwise
  10376. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  10377. 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){
  10378. ggml_tensor * node = cgraph->nodes[node_idx];
  10379. if (ggml_is_empty(node) || ggml_op_is_empty(node->op) || !node->buffer) {
  10380. return false;
  10381. }
  10382. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  10383. ctx->semaphore_idx = 0;
  10384. ggml_tensor * src0 = node->src[0];
  10385. ggml_tensor * src1 = node->src[1];
  10386. ggml_tensor * src2 = node->src[2];
  10387. ggml_tensor * src3 = node->src[3];
  10388. if (node->op == GGML_OP_ADD) {
  10389. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  10390. if (next_node_idx < cgraph->n_nodes &&
  10391. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  10392. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  10393. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  10394. ctx->device->add_rms_fusion) {
  10395. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  10396. ctx->do_add_rms_partials_offset_calculation = true;
  10397. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  10398. ctx->do_add_rms_partials = true;
  10399. }
  10400. }
  10401. }
  10402. vk_context compute_ctx;
  10403. if (ctx->compute_ctx.expired()) {
  10404. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10405. ctx->compute_ctx = compute_ctx;
  10406. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10407. } else {
  10408. compute_ctx = ctx->compute_ctx.lock();
  10409. }
  10410. {
  10411. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  10412. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  10413. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  10414. // outside of this logic. When a node uses one of the prealloc buffers for something like
  10415. // dequantization or split_k, additional synchronization is needed between those passes.
  10416. bool need_sync = false;
  10417. // Check whether "node" requires synchronization. The node requires synchronization if it
  10418. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  10419. // Destination nodes are checked against both the written/read lists. Source nodes are only
  10420. // checked against the written list. Two nodes overlap in memory if they come from the same
  10421. // buffer and the tensor or view ranges overlap.
  10422. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  10423. if (unsynced_nodes.size() == 0) {
  10424. return false;
  10425. }
  10426. auto n_base = vk_tensor_offset(node) + node->view_offs;
  10427. auto n_size = ggml_nbytes(node);
  10428. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  10429. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10430. for (auto &other : unsynced_nodes) {
  10431. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  10432. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  10433. if (a_buf == o_buf) {
  10434. auto o_base = vk_tensor_offset(other) + other->view_offs;
  10435. auto o_size = ggml_nbytes(other);
  10436. if ((o_base <= n_base && n_base < o_base + o_size) ||
  10437. (n_base <= o_base && o_base < n_base + n_size)) {
  10438. return true;
  10439. }
  10440. }
  10441. }
  10442. return false;
  10443. };
  10444. // For all fused ops, check if the destination node or any of the source
  10445. // nodes require synchronization.
  10446. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  10447. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10448. // If the node actually writes to memory, then check if it needs to sync
  10449. if (ctx->fused_ops_write_mask & (1 << i)) {
  10450. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  10451. need_sync = true;
  10452. break;
  10453. }
  10454. }
  10455. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10456. if (!cur_node->src[j]) {
  10457. continue;
  10458. }
  10459. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  10460. need_sync = true;
  10461. break;
  10462. }
  10463. }
  10464. }
  10465. if (need_sync) {
  10466. if (vk_enable_sync_logger) {
  10467. std::cerr << "sync" << std::endl;
  10468. }
  10469. ctx->unsynced_nodes_written.clear();
  10470. ctx->unsynced_nodes_read.clear();
  10471. ggml_vk_sync_buffers(ctx, compute_ctx);
  10472. if (vk_perf_logger_enabled && vk_perf_logger_concurrent) {
  10473. ctx->query_node_idx[ctx->query_idx] = node_idx;
  10474. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  10475. }
  10476. }
  10477. // Add all fused nodes to the unsynchronized lists.
  10478. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10479. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10480. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  10481. if (ctx->fused_ops_write_mask & (1 << i)) {
  10482. ctx->unsynced_nodes_written.push_back(cur_node);
  10483. }
  10484. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10485. if (!cur_node->src[j]) {
  10486. continue;
  10487. }
  10488. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  10489. }
  10490. }
  10491. }
  10492. if (vk_enable_sync_logger) {
  10493. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10494. auto *n = cgraph->nodes[node_idx + i];
  10495. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  10496. if (n->op == GGML_OP_GLU) {
  10497. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  10498. }
  10499. if (n->op == GGML_OP_ROPE) {
  10500. const int mode = ((const int32_t *) n->op_params)[2];
  10501. std::cerr << " rope mode: " << mode;
  10502. }
  10503. std::cerr << std::endl;
  10504. }
  10505. }
  10506. switch (node->op) {
  10507. case GGML_OP_REPEAT:
  10508. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  10509. break;
  10510. case GGML_OP_REPEAT_BACK:
  10511. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  10512. break;
  10513. case GGML_OP_ACC:
  10514. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  10515. break;
  10516. case GGML_OP_GET_ROWS:
  10517. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  10518. break;
  10519. case GGML_OP_ADD:
  10520. if (ctx->num_additional_fused_ops) {
  10521. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  10522. } else {
  10523. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  10524. }
  10525. break;
  10526. case GGML_OP_SUB:
  10527. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  10528. break;
  10529. case GGML_OP_MUL:
  10530. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  10531. break;
  10532. case GGML_OP_DIV:
  10533. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  10534. break;
  10535. case GGML_OP_ADD_ID:
  10536. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  10537. break;
  10538. case GGML_OP_CONCAT:
  10539. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  10540. break;
  10541. case GGML_OP_UPSCALE:
  10542. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  10543. break;
  10544. case GGML_OP_ADD1:
  10545. ggml_vk_add1(ctx, compute_ctx, src0, src1, node);
  10546. break;
  10547. case GGML_OP_ARANGE:
  10548. ggml_vk_arange(ctx, compute_ctx, node);
  10549. break;
  10550. case GGML_OP_FILL:
  10551. ggml_vk_fill(ctx, compute_ctx, node);
  10552. break;
  10553. case GGML_OP_SCALE:
  10554. ggml_vk_scale(ctx, compute_ctx, src0, node);
  10555. break;
  10556. case GGML_OP_SQR:
  10557. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  10558. break;
  10559. case GGML_OP_SQRT:
  10560. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  10561. break;
  10562. case GGML_OP_SIN:
  10563. ggml_vk_sin(ctx, compute_ctx, src0, node);
  10564. break;
  10565. case GGML_OP_COS:
  10566. ggml_vk_cos(ctx, compute_ctx, src0, node);
  10567. break;
  10568. case GGML_OP_LOG:
  10569. ggml_vk_log(ctx, compute_ctx, src0, node);
  10570. break;
  10571. case GGML_OP_TRI:
  10572. ggml_vk_tri(ctx, compute_ctx, src0, node);
  10573. break;
  10574. case GGML_OP_DIAG:
  10575. ggml_vk_diag(ctx, compute_ctx, src0, node);
  10576. break;
  10577. case GGML_OP_CLAMP:
  10578. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  10579. break;
  10580. case GGML_OP_PAD:
  10581. ggml_vk_pad(ctx, compute_ctx, src0, node);
  10582. break;
  10583. case GGML_OP_ROLL:
  10584. ggml_vk_roll(ctx, compute_ctx, src0, node);
  10585. break;
  10586. case GGML_OP_CPY:
  10587. case GGML_OP_CONT:
  10588. case GGML_OP_DUP:
  10589. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  10590. break;
  10591. case GGML_OP_SET_ROWS:
  10592. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  10593. break;
  10594. case GGML_OP_SILU_BACK:
  10595. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  10596. break;
  10597. case GGML_OP_NORM:
  10598. ggml_vk_norm(ctx, compute_ctx, src0, node);
  10599. break;
  10600. case GGML_OP_GROUP_NORM:
  10601. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  10602. break;
  10603. case GGML_OP_RMS_NORM:
  10604. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  10605. break;
  10606. case GGML_OP_RMS_NORM_BACK:
  10607. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  10608. break;
  10609. case GGML_OP_L2_NORM:
  10610. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  10611. break;
  10612. case GGML_OP_UNARY:
  10613. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10614. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10615. break;
  10616. }
  10617. switch (ggml_get_unary_op(node)) {
  10618. case GGML_UNARY_OP_EXP:
  10619. case GGML_UNARY_OP_SILU:
  10620. case GGML_UNARY_OP_GELU:
  10621. case GGML_UNARY_OP_GELU_ERF:
  10622. case GGML_UNARY_OP_GELU_QUICK:
  10623. case GGML_UNARY_OP_RELU:
  10624. case GGML_UNARY_OP_NEG:
  10625. case GGML_UNARY_OP_TANH:
  10626. case GGML_UNARY_OP_SIGMOID:
  10627. case GGML_UNARY_OP_HARDSIGMOID:
  10628. case GGML_UNARY_OP_HARDSWISH:
  10629. case GGML_UNARY_OP_ABS:
  10630. case GGML_UNARY_OP_SOFTPLUS:
  10631. case GGML_UNARY_OP_STEP:
  10632. case GGML_UNARY_OP_ROUND:
  10633. case GGML_UNARY_OP_CEIL:
  10634. case GGML_UNARY_OP_FLOOR:
  10635. case GGML_UNARY_OP_TRUNC:
  10636. ggml_vk_unary(ctx, compute_ctx, src0, node);
  10637. break;
  10638. case GGML_UNARY_OP_XIELU:
  10639. ggml_vk_xielu(ctx, compute_ctx, src0, node);
  10640. break;
  10641. default:
  10642. return false;
  10643. }
  10644. break;
  10645. case GGML_OP_GLU:
  10646. switch (ggml_get_glu_op(node)) {
  10647. case GGML_GLU_OP_GEGLU:
  10648. case GGML_GLU_OP_REGLU:
  10649. case GGML_GLU_OP_SWIGLU:
  10650. case GGML_GLU_OP_SWIGLU_OAI:
  10651. case GGML_GLU_OP_GEGLU_ERF:
  10652. case GGML_GLU_OP_GEGLU_QUICK:
  10653. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  10654. break;
  10655. default:
  10656. return false;
  10657. }
  10658. break;
  10659. case GGML_OP_DIAG_MASK_INF:
  10660. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  10661. break;
  10662. case GGML_OP_SOFT_MAX:
  10663. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10664. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10665. } else {
  10666. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  10667. }
  10668. break;
  10669. case GGML_OP_SOFT_MAX_BACK:
  10670. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  10671. break;
  10672. case GGML_OP_ROPE:
  10673. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  10674. break;
  10675. case GGML_OP_ROPE_BACK:
  10676. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  10677. break;
  10678. case GGML_OP_ARGSORT:
  10679. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10680. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10681. } else {
  10682. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10683. }
  10684. break;
  10685. case GGML_OP_TOP_K:
  10686. ggml_vk_topk(ctx, compute_ctx, src0, node);
  10687. break;
  10688. case GGML_OP_SUM:
  10689. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10690. break;
  10691. case GGML_OP_SUM_ROWS:
  10692. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10693. break;
  10694. case GGML_OP_CUMSUM:
  10695. ggml_vk_cumsum(ctx, compute_ctx, src0, node);
  10696. break;
  10697. case GGML_OP_MEAN:
  10698. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10699. break;
  10700. case GGML_OP_ARGMAX:
  10701. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10702. break;
  10703. case GGML_OP_COUNT_EQUAL:
  10704. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10705. break;
  10706. case GGML_OP_SOLVE_TRI:
  10707. ggml_vk_solve_tri(ctx, compute_ctx, src0, src1, node);
  10708. break;
  10709. case GGML_OP_IM2COL:
  10710. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10711. break;
  10712. case GGML_OP_IM2COL_3D:
  10713. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10714. break;
  10715. case GGML_OP_TIMESTEP_EMBEDDING:
  10716. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10717. break;
  10718. case GGML_OP_CONV_TRANSPOSE_1D:
  10719. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10720. break;
  10721. case GGML_OP_POOL_2D:
  10722. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10723. break;
  10724. case GGML_OP_CONV_2D:
  10725. case GGML_OP_CONV_TRANSPOSE_2D:
  10726. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10727. break;
  10728. case GGML_OP_CONV_2D_DW:
  10729. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10730. break;
  10731. case GGML_OP_LEAKY_RELU:
  10732. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10733. break;
  10734. case GGML_OP_MUL_MAT:
  10735. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10736. break;
  10737. case GGML_OP_MUL_MAT_ID:
  10738. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10739. break;
  10740. case GGML_OP_FLASH_ATTN_EXT:
  10741. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10742. break;
  10743. case GGML_OP_RWKV_WKV6:
  10744. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10745. break;
  10746. case GGML_OP_RWKV_WKV7:
  10747. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10748. break;
  10749. case GGML_OP_SSM_SCAN:
  10750. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10751. break;
  10752. case GGML_OP_SSM_CONV:
  10753. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10754. break;
  10755. case GGML_OP_OPT_STEP_ADAMW:
  10756. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10757. break;
  10758. case GGML_OP_OPT_STEP_SGD:
  10759. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10760. break;
  10761. default:
  10762. return false;
  10763. }
  10764. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10765. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10766. // Force context reset on each node so that each tensor ends up in its own context
  10767. // and can be run and compared to its CPU equivalent separately
  10768. last_node = true;
  10769. #endif
  10770. if (submit || last_node) {
  10771. ggml_vk_ctx_end(compute_ctx);
  10772. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10773. if (last_node) {
  10774. compute_ctx->exit_tensor_idx = node_idx_begin;
  10775. }
  10776. else {
  10777. compute_ctx->exit_tensor_idx = -1;
  10778. }
  10779. ctx->compute_ctx.reset();
  10780. ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready);
  10781. }
  10782. return true;
  10783. }
  10784. static void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready = false) {
  10785. GGML_UNUSED(cgraph);
  10786. GGML_UNUSED(tensor);
  10787. 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 << ")");
  10788. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10789. // Only run if ctx hasn't been submitted yet
  10790. if (!subctx->seqs.empty()) {
  10791. #ifdef GGML_VULKAN_CHECK_RESULTS
  10792. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10793. #endif
  10794. // Do staging buffer copies
  10795. for (auto& cpy : subctx->in_memcpys) {
  10796. memcpy(cpy.dst, cpy.src, cpy.n);
  10797. }
  10798. for (auto& mset : subctx->memsets) {
  10799. memset(mset.dst, mset.val, mset.n);
  10800. }
  10801. if (almost_ready && !ctx->almost_ready_fence_pending) {
  10802. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10803. ctx->almost_ready_fence_pending = true;
  10804. } else {
  10805. ggml_vk_submit(subctx, {});
  10806. }
  10807. ctx->submit_pending = true;
  10808. #ifdef GGML_VULKAN_CHECK_RESULTS
  10809. ggml_vk_synchronize(ctx);
  10810. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10811. #endif
  10812. }
  10813. if (tensor_idx == subctx->exit_tensor_idx) {
  10814. // Do staging buffer copies
  10815. for (auto& cpy : subctx->out_memcpys) {
  10816. memcpy(cpy.dst, cpy.src, cpy.n);
  10817. }
  10818. subctx->in_memcpys.clear();
  10819. subctx->out_memcpys.clear();
  10820. subctx->memsets.clear();
  10821. }
  10822. }
  10823. // Clean up after graph processing is done
  10824. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10825. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10826. ctx->prealloc_y_last_pipeline_used = {};
  10827. ctx->unsynced_nodes_written.clear();
  10828. ctx->unsynced_nodes_read.clear();
  10829. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10830. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10831. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10832. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10833. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10834. }
  10835. ctx->gc.semaphores.clear();
  10836. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10837. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10838. }
  10839. ctx->gc.tl_semaphores.clear();
  10840. ctx->semaphore_idx = 0;
  10841. ctx->event_idx = 0;
  10842. for (auto& event : ctx->gc.events) {
  10843. ctx->device->device.resetEvent(event);
  10844. }
  10845. ctx->tensor_ctxs.clear();
  10846. ctx->gc.contexts.clear();
  10847. ctx->pipeline_descriptor_set_requirements = 0;
  10848. ctx->descriptor_set_idx = 0;
  10849. }
  10850. // Clean up on backend free
  10851. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10852. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10853. // discard any unsubmitted command buffers
  10854. ctx->transfer_ctx.reset();
  10855. // wait for any pending command buffers to finish
  10856. ggml_vk_synchronize(ctx);
  10857. ggml_vk_graph_cleanup(ctx);
  10858. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10859. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10860. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10861. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10862. ggml_vk_destroy_buffer(ctx->sync_staging);
  10863. ctx->prealloc_y_last_pipeline_used = nullptr;
  10864. ctx->prealloc_size_x = 0;
  10865. ctx->prealloc_size_y = 0;
  10866. ctx->prealloc_size_split_k = 0;
  10867. for (auto& event : ctx->gc.events) {
  10868. ctx->device->device.destroyEvent(event);
  10869. }
  10870. ctx->gc.events.clear();
  10871. ctx->device->device.destroyFence(ctx->fence);
  10872. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10873. for (auto& pool : ctx->descriptor_pools) {
  10874. ctx->device->device.destroyDescriptorPool(pool);
  10875. }
  10876. ctx->descriptor_pools.clear();
  10877. ctx->descriptor_sets.clear();
  10878. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10879. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10880. if (vk_perf_logger_enabled) {
  10881. ctx->perf_logger->print_timings(true);
  10882. }
  10883. }
  10884. static int ggml_vk_get_device_count() {
  10885. ggml_vk_instance_init();
  10886. return vk_instance.device_indices.size();
  10887. }
  10888. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10889. ggml_vk_instance_init();
  10890. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10891. vk::PhysicalDeviceProperties props;
  10892. devices[device].getProperties(&props);
  10893. snprintf(description, description_size, "%s", props.deviceName.data());
  10894. }
  10895. // backend interface
  10896. #define UNUSED GGML_UNUSED
  10897. // device backend
  10898. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10899. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10900. }
  10901. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10902. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10903. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10904. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10905. delete ctx;
  10906. }
  10907. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10908. return vk_ptr_base;
  10909. UNUSED(buffer);
  10910. }
  10911. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10912. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10913. if (tensor->view_src != nullptr) {
  10914. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10915. }
  10916. return GGML_STATUS_SUCCESS;
  10917. }
  10918. 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) {
  10919. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10920. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10921. vk_buffer buf = buf_ctx->dev_buffer;
  10922. uint32_t val32 = (uint32_t)value * 0x01010101;
  10923. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10924. }
  10925. 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) {
  10926. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10927. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10928. vk_buffer buf = buf_ctx->dev_buffer;
  10929. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10930. }
  10931. 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) {
  10932. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10933. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10934. vk_buffer buf = buf_ctx->dev_buffer;
  10935. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10936. }
  10937. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10938. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10939. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10940. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10941. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10942. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10943. 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));
  10944. return true;
  10945. }
  10946. return false;
  10947. UNUSED(buffer);
  10948. }
  10949. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10950. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10951. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10952. }
  10953. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10954. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10955. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10956. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10957. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10958. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10959. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10960. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10961. /* .clear = */ ggml_backend_vk_buffer_clear,
  10962. /* .reset = */ NULL,
  10963. };
  10964. // vk buffer type
  10965. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10966. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10967. return ctx->name.c_str();
  10968. }
  10969. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10970. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10971. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10972. vk_buffer dev_buffer = nullptr;
  10973. try {
  10974. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10975. } catch (const vk::SystemError& e) {
  10976. return nullptr;
  10977. }
  10978. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10979. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10980. }
  10981. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10982. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10983. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10984. }
  10985. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10986. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10987. return ctx->device->suballocation_block_size;
  10988. }
  10989. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10990. return ggml_nbytes(tensor);
  10991. UNUSED(buft);
  10992. }
  10993. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10994. ggml_vk_instance_init();
  10995. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10996. vk_device dev = ggml_vk_get_device(dev_num);
  10997. return &dev->buffer_type;
  10998. }
  10999. // host buffer type
  11000. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  11001. return GGML_VK_NAME "_Host";
  11002. UNUSED(buft);
  11003. }
  11004. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  11005. return GGML_VK_NAME "_Host";
  11006. UNUSED(buffer);
  11007. }
  11008. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  11009. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  11010. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  11011. }
  11012. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  11013. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  11014. size += 32; // Behave like the CPU buffer type
  11015. void * ptr = nullptr;
  11016. try {
  11017. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  11018. } catch (vk::SystemError& e) {
  11019. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  11020. // fallback to cpu buffer
  11021. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  11022. }
  11023. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  11024. buffer->buft = buft;
  11025. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  11026. return buffer;
  11027. UNUSED(buft);
  11028. }
  11029. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  11030. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  11031. UNUSED(buft);
  11032. }
  11033. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  11034. return vk_instance.devices[0]->suballocation_block_size;
  11035. UNUSED(buft);
  11036. }
  11037. // Should be changed to return device-specific host buffer type
  11038. // but that probably requires changes in llama.cpp
  11039. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  11040. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  11041. /* .iface = */ {
  11042. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  11043. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  11044. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  11045. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  11046. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  11047. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  11048. },
  11049. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  11050. /* .context = */ nullptr,
  11051. };
  11052. // Make sure device 0 is initialized
  11053. ggml_vk_instance_init();
  11054. ggml_vk_get_device(0);
  11055. return &ggml_backend_vk_buffer_type_host;
  11056. }
  11057. // backend
  11058. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  11059. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11060. return ctx->name.c_str();
  11061. }
  11062. static void ggml_backend_vk_free(ggml_backend_t backend) {
  11063. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11064. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  11065. ggml_vk_cleanup(ctx);
  11066. delete ctx;
  11067. delete backend;
  11068. }
  11069. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  11070. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11071. return &ctx->device->buffer_type;
  11072. }
  11073. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  11074. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  11075. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11076. 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");
  11077. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11078. vk_context transfer_ctx;
  11079. if (ctx->transfer_ctx.expired()) {
  11080. // Initialize new transfer context
  11081. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11082. ctx->transfer_ctx = transfer_ctx;
  11083. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11084. } else {
  11085. transfer_ctx = ctx->transfer_ctx.lock();
  11086. }
  11087. vk_buffer buf = buf_ctx->dev_buffer;
  11088. auto dst_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  11089. bool ret = ggml_vk_buffer_write_async(transfer_ctx, buf, dst_offset, data, size);
  11090. if (!ret) {
  11091. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  11092. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  11093. vk::BufferCopy buffer_cpy;
  11094. buffer_cpy.srcOffset = 0;
  11095. buffer_cpy.dstOffset = dst_offset;
  11096. buffer_cpy.size = size;
  11097. transfer_ctx->s->buffer.copyBuffer(ctx->sync_staging->buffer, buf->buffer, { buffer_cpy });
  11098. deferred_memcpy(ctx->sync_staging->ptr, data, size, &transfer_ctx->in_memcpys);
  11099. ggml_vk_synchronize(ctx);
  11100. }
  11101. }
  11102. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  11103. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  11104. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11105. 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");
  11106. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11107. vk_context transfer_ctx;
  11108. if (ctx->transfer_ctx.expired()) {
  11109. // Initialize new transfer context
  11110. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11111. ctx->transfer_ctx = transfer_ctx;
  11112. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11113. } else {
  11114. transfer_ctx = ctx->transfer_ctx.lock();
  11115. }
  11116. vk_buffer buf = buf_ctx->dev_buffer;
  11117. auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  11118. bool ret = ggml_vk_buffer_read_async(transfer_ctx, buf, src_offset, data, size);
  11119. // If that failed, copy synchronously through a staging buffer
  11120. if (!ret) {
  11121. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  11122. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  11123. vk::BufferCopy buffer_cpy;
  11124. buffer_cpy.srcOffset = src_offset;
  11125. buffer_cpy.dstOffset = 0;
  11126. buffer_cpy.size = size;
  11127. transfer_ctx->s->buffer.copyBuffer(buf->buffer, ctx->sync_staging->buffer, { buffer_cpy });
  11128. deferred_memcpy(data, ctx->sync_staging->ptr, size, &transfer_ctx->out_memcpys);
  11129. ggml_vk_synchronize(ctx);
  11130. }
  11131. }
  11132. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  11133. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  11134. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11135. 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)) {
  11136. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  11137. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  11138. vk_context transfer_ctx;
  11139. if (ctx->transfer_ctx.expired()) {
  11140. // Initialize new transfer context
  11141. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11142. ctx->transfer_ctx = transfer_ctx;
  11143. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11144. } else {
  11145. transfer_ctx = ctx->transfer_ctx.lock();
  11146. }
  11147. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  11148. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  11149. 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));
  11150. return true;
  11151. }
  11152. return false;
  11153. }
  11154. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx) {
  11155. VK_LOG_DEBUG("ggml_vk_synchronize()");
  11156. bool do_transfer = !ctx->transfer_ctx.expired();
  11157. vk_context transfer_ctx;
  11158. if (do_transfer) {
  11159. transfer_ctx = ctx->transfer_ctx.lock();
  11160. ggml_vk_ctx_end(transfer_ctx);
  11161. for (auto& cpy : transfer_ctx->in_memcpys) {
  11162. memcpy(cpy.dst, cpy.src, cpy.n);
  11163. }
  11164. ggml_vk_submit(transfer_ctx, {});
  11165. ctx->submit_pending = true;
  11166. }
  11167. if (ctx->submit_pending) {
  11168. {
  11169. std::lock_guard<std::mutex> guard(queue_mutex);
  11170. ctx->device->compute_queue.queue.submit({}, ctx->fence);
  11171. }
  11172. ggml_vk_wait_for_fence(ctx);
  11173. ctx->submit_pending = false;
  11174. }
  11175. if (do_transfer) {
  11176. for (auto& cpy : transfer_ctx->out_memcpys) {
  11177. memcpy(cpy.dst, cpy.src, cpy.n);
  11178. }
  11179. ctx->transfer_ctx.reset();
  11180. }
  11181. }
  11182. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  11183. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  11184. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11185. ggml_vk_synchronize(ctx);
  11186. ggml_vk_graph_cleanup(ctx);
  11187. }
  11188. static bool ggml_vk_is_empty(ggml_tensor * node) {
  11189. 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;
  11190. }
  11191. 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) {
  11192. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  11193. return false;
  11194. }
  11195. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  11196. // additional constraints specific to this fusion
  11197. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  11198. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11199. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  11200. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  11201. // rms_norm only supports f32
  11202. if (mul->src[0]->type != GGML_TYPE_F32 ||
  11203. mul->src[1]->type != GGML_TYPE_F32 ||
  11204. mul->type != GGML_TYPE_F32) {
  11205. return false;
  11206. }
  11207. // if rms_norm is the B operand, then we don't handle broadcast
  11208. if (rms_norm == mul->src[1] &&
  11209. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  11210. return false;
  11211. }
  11212. // rms_norm shader assumes contiguous rows
  11213. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  11214. return false;
  11215. }
  11216. }
  11217. auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) {
  11218. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  11219. // mat-vec only
  11220. if (ggml_nrows(mul) != 1) {
  11221. return false;
  11222. }
  11223. // shaders assume the types match
  11224. if (mul->type != bias->type) {
  11225. return false;
  11226. }
  11227. // shaders reuse the D shape for bias
  11228. if (!ggml_are_same_shape(mul, bias) ||
  11229. !ggml_are_same_stride(mul, bias)) {
  11230. return false;
  11231. }
  11232. // unaligned bias isn't handled
  11233. if (get_misalign_bytes(ctx, bias) != 0) {
  11234. return false;
  11235. }
  11236. return true;
  11237. };
  11238. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  11239. // additional constraints specific to this fusion
  11240. const ggml_tensor *mul = cgraph->nodes[node_idx];
  11241. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  11242. if (!mm_add_ok(mul, add)) {
  11243. return false;
  11244. }
  11245. if (ops.size() == 3) {
  11246. if (ops.begin()[2] != GGML_OP_ADD) {
  11247. return false;
  11248. }
  11249. if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) {
  11250. return false;
  11251. }
  11252. }
  11253. }
  11254. auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) {
  11255. const ggml_tensor *scale = mul->src[1];
  11256. if (mmid != mul->src[0]) {
  11257. return false;
  11258. }
  11259. // mat-vec only
  11260. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  11261. return false;
  11262. }
  11263. // shaders assume the types match
  11264. if (mmid->type != scale->type) {
  11265. return false;
  11266. }
  11267. // shaders assume the bias is contiguous
  11268. if (!ggml_is_contiguous(scale)) {
  11269. return false;
  11270. }
  11271. // unaligned bias isn't handled
  11272. if (get_misalign_bytes(ctx, scale) != 0) {
  11273. return false;
  11274. }
  11275. // shader only indexes by expert index
  11276. if (scale->ne[0] != 1 ||
  11277. scale->ne[1] != mul->ne[1] ||
  11278. scale->ne[2] != 1 ||
  11279. scale->ne[3] != 1) {
  11280. return false;
  11281. }
  11282. return true;
  11283. };
  11284. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  11285. // additional constraints specific to this fusion
  11286. const ggml_tensor *mul = cgraph->nodes[node_idx];
  11287. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  11288. const ggml_tensor *bias = add->src[1];
  11289. if (mul != add->src[0]) {
  11290. return false;
  11291. }
  11292. // mat-vec only
  11293. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  11294. return false;
  11295. }
  11296. // shaders assume the types match
  11297. if (mul->type != bias->type) {
  11298. return false;
  11299. }
  11300. // shaders assume the bias is contiguous
  11301. if (!ggml_is_contiguous(bias)) {
  11302. return false;
  11303. }
  11304. // the ID tensor must be the same for mul_mat_id and add_id
  11305. if (mul->src[2] != add->src[2]) {
  11306. return false;
  11307. }
  11308. // unaligned bias isn't handled
  11309. if (get_misalign_bytes(ctx, bias) != 0) {
  11310. return false;
  11311. }
  11312. if (ops.size() == 3) {
  11313. if (ops.begin()[2] != GGML_OP_MUL) {
  11314. return false;
  11315. }
  11316. const ggml_tensor *mul = cgraph->nodes[node_idx + 2];
  11317. return mmid_mul_ok(add, mul);
  11318. }
  11319. }
  11320. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  11321. // additional constraints specific to this fusion
  11322. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  11323. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11324. if (!mmid_mul_ok(mmid, mul)) {
  11325. return false;
  11326. }
  11327. }
  11328. return true;
  11329. }
  11330. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11331. int node_idx, topk_moe_mode mode) {
  11332. const ggml_tensor * softmax;
  11333. const ggml_tensor * weights;
  11334. const ggml_tensor * get_rows;
  11335. const ggml_tensor * argsort;
  11336. switch (mode) {
  11337. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  11338. softmax = cgraph->nodes[node_idx + 0];
  11339. weights = cgraph->nodes[node_idx + 9];
  11340. get_rows = cgraph->nodes[node_idx + 4];
  11341. argsort = cgraph->nodes[node_idx + 2];
  11342. break;
  11343. case TOPK_MOE_SIGMOID_NORM_BIAS:
  11344. softmax = cgraph->nodes[node_idx + 0]; // really sigmoid
  11345. weights = cgraph->nodes[node_idx + 10];
  11346. get_rows = cgraph->nodes[node_idx + 5];
  11347. argsort = cgraph->nodes[node_idx + 3];
  11348. if (ggml_get_unary_op(softmax) != GGML_UNARY_OP_SIGMOID) {
  11349. return false;
  11350. }
  11351. // bias is expected to be 1D
  11352. if (ggml_nrows(cgraph->nodes[node_idx + 2]->src[1]) != 1 ||
  11353. !ggml_is_contiguous(cgraph->nodes[node_idx + 2]->src[1])) {
  11354. return false;
  11355. }
  11356. // sigmoid fusion seems to generate infinities on moltenvk
  11357. if (ctx->device->driver_id == vk::DriverId::eMoltenvk) {
  11358. return false;
  11359. }
  11360. break;
  11361. case TOPK_MOE_EARLY_SOFTMAX:
  11362. softmax = cgraph->nodes[node_idx + 0];
  11363. weights = cgraph->nodes[node_idx + 4];
  11364. get_rows = cgraph->nodes[node_idx + 4];
  11365. argsort = cgraph->nodes[node_idx + 2];
  11366. break;
  11367. case TOPK_MOE_LATE_SOFTMAX:
  11368. softmax = cgraph->nodes[node_idx + 4];
  11369. weights = cgraph->nodes[node_idx + 5];
  11370. get_rows = cgraph->nodes[node_idx + 2];
  11371. argsort = cgraph->nodes[node_idx + 0];
  11372. break;
  11373. default:
  11374. return false;
  11375. }
  11376. ggml_tensor * probs = get_rows->src[0];
  11377. if (probs->op != GGML_OP_RESHAPE) {
  11378. return false;
  11379. }
  11380. probs = probs->src[0];
  11381. ggml_tensor * selection_probs = argsort->src[0];
  11382. if (probs != selection_probs && mode != TOPK_MOE_SIGMOID_NORM_BIAS) {
  11383. return false;
  11384. }
  11385. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  11386. return false;
  11387. }
  11388. if (softmax->op == GGML_OP_SOFT_MAX) {
  11389. const float * op_params = (const float *)softmax->op_params;
  11390. float scale = op_params[0];
  11391. float max_bias = op_params[1];
  11392. if (scale != 1.0f || max_bias != 0.0f) {
  11393. return false;
  11394. }
  11395. // don't fuse when masks or sinks are present
  11396. if (softmax->src[1] || softmax->src[2]) {
  11397. return false;
  11398. }
  11399. }
  11400. const int n_expert = softmax->ne[0];
  11401. if (n_expert > (1 << (num_topk_moe_pipelines-1))) {
  11402. return false;
  11403. }
  11404. if (!ctx->device->subgroup_arithmetic ||
  11405. !ctx->device->subgroup_shuffle ||
  11406. !ctx->device->subgroup_require_full_support ||
  11407. ctx->device->disable_fusion) {
  11408. return false;
  11409. }
  11410. return true;
  11411. }
  11412. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11413. int node_idx) {
  11414. GGML_UNUSED(ctx);
  11415. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  11416. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  11417. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  11418. // ne3 not tested
  11419. if (rope->src[0]->ne[3] != 1) {
  11420. return false;
  11421. }
  11422. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  11423. return false;
  11424. }
  11425. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  11426. return false;
  11427. }
  11428. // The view should flatten two dims of rope into one dim
  11429. if (!ggml_is_contiguous(view) ||
  11430. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  11431. return false;
  11432. }
  11433. // Only norm/neox/mrope shaders have the fusion code
  11434. const int mode = ((const int32_t *) rope->op_params)[2];
  11435. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_MROPE) {
  11436. return false;
  11437. }
  11438. return true;
  11439. }
  11440. // Check whether the tensors overlap in memory but are not equal.
  11441. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  11442. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  11443. // to overlap if they are exactly equal.
  11444. // XXX TODO this check is probably missing from several fusion optimizations.
  11445. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  11446. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  11447. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  11448. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  11449. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  11450. if (a_buf == b_buf) {
  11451. auto a_base = vk_tensor_offset(a) + a->view_offs;
  11452. auto a_size = ggml_nbytes(a);
  11453. auto b_base = vk_tensor_offset(b) + b->view_offs;
  11454. auto b_size = ggml_nbytes(b);
  11455. if (a_base == b_base && a_size == b_size) {
  11456. return false;
  11457. }
  11458. if ((b_base <= a_base && a_base < b_base + b_size) ||
  11459. (a_base <= b_base && b_base < a_base + a_size)) {
  11460. return true;
  11461. }
  11462. }
  11463. return false;
  11464. }
  11465. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11466. int node_idx) {
  11467. GGML_UNUSED(ctx);
  11468. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  11469. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11470. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  11471. const int mode = ((const int32_t *) rope->op_params)[2];
  11472. // noncontig tensors aren't tested, and don't seem common in practice
  11473. if (!ggml_is_contiguous(rms) ||
  11474. !ggml_is_contiguous(mul) ||
  11475. !ggml_is_contiguous(rope)) {
  11476. return false;
  11477. }
  11478. // only norm/neox are handled in the shader
  11479. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  11480. return false;
  11481. }
  11482. // shared memory size for passing data from mul->rope
  11483. if (mul->ne[0] > 1024) {
  11484. return false;
  11485. }
  11486. // must not overwrite srcs in a way that's not elementwise
  11487. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  11488. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  11489. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  11490. return false;
  11491. }
  11492. // conditions for pipeline creation
  11493. if (!(ctx->device->float_controls_rte_fp16 &&
  11494. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= ctx->device->properties.limits.maxPushConstantsSize)) {
  11495. return false;
  11496. }
  11497. return true;
  11498. }
  11499. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  11500. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  11501. if (first_node->op != GGML_OP_ADD) {
  11502. return 0;
  11503. }
  11504. if (!ctx->device->multi_add) {
  11505. return 0;
  11506. }
  11507. int32_t num_adds = 1;
  11508. while (node_idx + num_adds < cgraph->n_nodes &&
  11509. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  11510. num_adds < MAX_FUSED_ADDS) {
  11511. num_adds++;
  11512. }
  11513. // The shader currently requires same shapes (but different strides are allowed),
  11514. // everything f32, and no misalignment
  11515. for (int32_t i = 0; i < num_adds; ++i) {
  11516. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  11517. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  11518. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  11519. next_node->type != GGML_TYPE_F32 ||
  11520. next_node->src[0]->type != GGML_TYPE_F32 ||
  11521. next_node->src[1]->type != GGML_TYPE_F32 ||
  11522. get_misalign_bytes(ctx, next_node) ||
  11523. get_misalign_bytes(ctx, next_node->src[0]) ||
  11524. get_misalign_bytes(ctx, next_node->src[1])) {
  11525. num_adds = i;
  11526. }
  11527. }
  11528. // Verify we can fuse these
  11529. ggml_op adds[MAX_FUSED_ADDS];
  11530. for (int32_t i = 0; i < num_adds; ++i) {
  11531. adds[i] = GGML_OP_ADD;
  11532. }
  11533. // decrease num_adds if they can't all be fused
  11534. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  11535. num_adds--;
  11536. }
  11537. // a single add is not "fused", so just return zero
  11538. if (num_adds == 1) {
  11539. return 0;
  11540. }
  11541. return num_adds;
  11542. }
  11543. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  11544. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  11545. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11546. if (vk_instance.debug_utils_support) {
  11547. vk::DebugUtilsLabelEXT dul = {};
  11548. dul.pLabelName = "ggml_backend_vk_graph_compute";
  11549. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  11550. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  11551. }
  11552. ctx->prealloc_size_add_rms_partials_offset = 0;
  11553. ctx->do_add_rms_partials = false;
  11554. ctx->do_add_rms_partials_offset_calculation = false;
  11555. int last_node = cgraph->n_nodes - 1;
  11556. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  11557. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  11558. last_node -= 1;
  11559. }
  11560. // Reserve tensor context space for all nodes
  11561. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  11562. bool first_node_in_batch = true; // true if next node will be first node in a batch
  11563. int submit_node_idx = 0; // index to first node in a batch
  11564. vk_context compute_ctx;
  11565. if (vk_perf_logger_enabled) {
  11566. // allocate/resize the query pool
  11567. if (ctx->num_queries < cgraph->n_nodes + 1) {
  11568. if (ctx->query_pool) {
  11569. ctx->device->device.destroyQueryPool(ctx->query_pool);
  11570. }
  11571. vk::QueryPoolCreateInfo query_create_info;
  11572. query_create_info.queryType = vk::QueryType::eTimestamp;
  11573. query_create_info.queryCount = cgraph->n_nodes + 100;
  11574. ctx->query_pool = ctx->device->device.createQueryPool(query_create_info);
  11575. ctx->num_queries = query_create_info.queryCount;
  11576. ctx->query_fusion_names.resize(ctx->num_queries);
  11577. ctx->query_fusion_node_count.resize(ctx->num_queries);
  11578. ctx->query_nodes.resize(ctx->num_queries);
  11579. ctx->query_node_idx.resize(ctx->num_queries);
  11580. }
  11581. ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1);
  11582. std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr);
  11583. std::fill(ctx->query_fusion_node_count.begin(), ctx->query_fusion_node_count.end(), 0);
  11584. std::fill(ctx->query_nodes.begin(), ctx->query_nodes.end(), nullptr);
  11585. std::fill(ctx->query_node_idx.begin(), ctx->query_node_idx.end(), 0);
  11586. GGML_ASSERT(ctx->compute_ctx.expired());
  11587. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11588. ctx->compute_ctx = compute_ctx;
  11589. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11590. ctx->query_idx = 0;
  11591. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11592. }
  11593. ctx->prealloc_y_last_pipeline_used = nullptr;
  11594. ctx->prealloc_y_last_tensor_used = nullptr;
  11595. if (ctx->prealloc_size_add_rms_partials) {
  11596. ggml_vk_preallocate_buffers(ctx, nullptr);
  11597. if (ctx->compute_ctx.expired()) {
  11598. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11599. ctx->compute_ctx = compute_ctx;
  11600. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11601. } else {
  11602. compute_ctx = ctx->compute_ctx.lock();
  11603. }
  11604. // initialize partial sums to zero.
  11605. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  11606. ggml_vk_sync_buffers(ctx, compute_ctx);
  11607. }
  11608. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  11609. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  11610. // (and scaled down based on model size, so smaller models submit earlier).
  11611. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  11612. int nodes_per_submit = 100;
  11613. int submitted_nodes = 0;
  11614. int submit_count = 0;
  11615. uint64_t mul_mat_bytes = 0;
  11616. uint64_t total_mul_mat_bytes = 0;
  11617. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  11618. for (int i = 0; i < cgraph->n_nodes; i++) {
  11619. if (first_node_in_batch) {
  11620. submit_node_idx = i;
  11621. }
  11622. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11623. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  11624. mul_mat_bytes += bytes;
  11625. total_mul_mat_bytes += bytes;
  11626. }
  11627. ctx->fused_topk_moe_mode = TOPK_MOE_COUNT;
  11628. ctx->fused_topk_moe_scale = false;
  11629. const char *fusion_string {};
  11630. if (!ctx->device->disable_fusion) {
  11631. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11632. if (num_adds) {
  11633. ctx->num_additional_fused_ops = num_adds - 1;
  11634. fusion_string = "MULTI_ADD";
  11635. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) {
  11636. ctx->num_additional_fused_ops = 2;
  11637. fusion_string = "MUL_MAT_ADD_ADD";
  11638. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11639. ctx->num_additional_fused_ops = 1;
  11640. fusion_string = "MUL_MAT_ADD";
  11641. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) {
  11642. ctx->num_additional_fused_ops = 2;
  11643. fusion_string = "MUL_MAT_ID_ADD_ID_MUL";
  11644. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11645. ctx->num_additional_fused_ops = 1;
  11646. fusion_string = "MUL_MAT_ID_ADD_ID";
  11647. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  11648. ctx->num_additional_fused_ops = 1;
  11649. fusion_string = "MUL_MAT_ID_MUL";
  11650. } 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 }) &&
  11651. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  11652. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  11653. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  11654. ctx->num_additional_fused_ops = 4;
  11655. fusion_string = "RMS_NORM_MUL_ROPE_VIEW_SET_ROWS";
  11656. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  11657. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  11658. ctx->num_additional_fused_ops = 2;
  11659. fusion_string = "RMS_NORM_MUL_ROPE";
  11660. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11661. ctx->num_additional_fused_ops = 1;
  11662. fusion_string = "RMS_NORM_MUL";
  11663. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11664. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11665. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11666. ctx->num_additional_fused_ops = 2;
  11667. fusion_string = "ROPE_VIEW_SET_ROWS";
  11668. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11669. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11670. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11671. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11672. // view of argsort writes to memory
  11673. ctx->fused_ops_write_mask |= 1 << 3;
  11674. ctx->fused_topk_moe_mode = TOPK_MOE_EARLY_SOFTMAX_NORM;
  11675. fusion_string = "TOPK_MOE_EARLY_SOFTMAX_NORM";
  11676. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_sigmoid_norm_bias, { i + 4, i + 10 }) &&
  11677. ggml_check_edges(cgraph, i, topk_moe_sigmoid_norm_bias_edges) &&
  11678. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_SIGMOID_NORM_BIAS)) {
  11679. ctx->num_additional_fused_ops = topk_moe_sigmoid_norm_bias.size() - 1;
  11680. // view of argsort writes to memory
  11681. ctx->fused_ops_write_mask |= 1 << 4;
  11682. ctx->fused_topk_moe_mode = TOPK_MOE_SIGMOID_NORM_BIAS;
  11683. fusion_string = "TOPK_MOE_SIGMOID_NORM_BIAS";
  11684. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11685. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11686. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11687. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11688. // view of argsort writes to memory
  11689. ctx->fused_ops_write_mask |= 1 << 3;
  11690. ctx->fused_topk_moe_mode = TOPK_MOE_EARLY_SOFTMAX;
  11691. fusion_string = "TOPK_MOE_EARLY_SOFTMAX";
  11692. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11693. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11694. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11695. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11696. // view of argsort writes to memory
  11697. ctx->fused_ops_write_mask |= 1 << 1;
  11698. ctx->fused_topk_moe_mode = TOPK_MOE_LATE_SOFTMAX;
  11699. fusion_string = "TOPK_MOE_LATE_SOFTMAX";
  11700. }
  11701. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  11702. // Look for an additional scale op to fuse - occurs in deepseek2 and nemotron3 nano.
  11703. if (ggml_can_fuse_subgraph(cgraph, i + ctx->num_additional_fused_ops - 1, { GGML_OP_DIV, GGML_OP_RESHAPE, GGML_OP_SCALE }, { i + ctx->num_additional_fused_ops + 1 }) ||
  11704. ggml_can_fuse_subgraph(cgraph, i + ctx->num_additional_fused_ops, { GGML_OP_GET_ROWS, GGML_OP_SCALE }, { i + ctx->num_additional_fused_ops + 1 })) {
  11705. ctx->fused_topk_moe_scale = true;
  11706. ctx->num_additional_fused_ops++;
  11707. }
  11708. }
  11709. }
  11710. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  11711. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  11712. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  11713. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11714. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11715. (i + ctx->num_additional_fused_ops >= last_node) ||
  11716. (almost_ready && !ctx->almost_ready_fence_pending);
  11717. 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);
  11718. if (vk_perf_logger_enabled && enqueued) {
  11719. if (ctx->compute_ctx.expired()) {
  11720. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11721. ctx->compute_ctx = compute_ctx;
  11722. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11723. } else {
  11724. compute_ctx = ctx->compute_ctx.lock();
  11725. }
  11726. if (!vk_perf_logger_concurrent) {
  11727. // track a single node/fusion for the current query
  11728. ctx->query_nodes[ctx->query_idx] = cgraph->nodes[i];
  11729. ctx->query_fusion_names[ctx->query_idx] = fusion_string;
  11730. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11731. } else {
  11732. // track a fusion string and number of fused ops for the current node_idx
  11733. ctx->query_fusion_names[i] = fusion_string;
  11734. ctx->query_fusion_node_count[i] = ctx->num_additional_fused_ops;
  11735. }
  11736. }
  11737. if (enqueued) {
  11738. ++submitted_nodes;
  11739. #ifndef GGML_VULKAN_CHECK_RESULTS
  11740. if (first_node_in_batch) {
  11741. first_node_in_batch = false;
  11742. }
  11743. #endif
  11744. }
  11745. if (submit && enqueued) {
  11746. first_node_in_batch = true;
  11747. submitted_nodes = 0;
  11748. mul_mat_bytes = 0;
  11749. if (submit_count < 3) {
  11750. mul_mat_bytes_per_submit *= 2;
  11751. }
  11752. submit_count++;
  11753. }
  11754. i += ctx->num_additional_fused_ops;
  11755. ctx->num_additional_fused_ops = 0;
  11756. ctx->fused_ops_write_mask = 0;
  11757. }
  11758. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11759. if (vk_perf_logger_enabled) {
  11760. // End the command buffer and submit/wait
  11761. GGML_ASSERT(!ctx->compute_ctx.expired());
  11762. compute_ctx = ctx->compute_ctx.lock();
  11763. ggml_vk_ctx_end(compute_ctx);
  11764. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11765. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11766. ctx->device->device.resetFences({ ctx->device->fence });
  11767. // Get the results and pass them to the logger
  11768. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11769. 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");
  11770. if (!vk_perf_logger_concurrent) {
  11771. // Log each op separately
  11772. for (int i = 1; i < ctx->query_idx; i++) {
  11773. auto node = ctx->query_nodes[i];
  11774. auto name = ctx->query_fusion_names[i];
  11775. ctx->perf_logger->log_timing(node, name, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11776. }
  11777. } else {
  11778. // Log each group of nodes
  11779. int prev_node_idx = 0;
  11780. for (int i = 1; i < ctx->query_idx; i++) {
  11781. auto cur_node_idx = ctx->query_node_idx[i];
  11782. std::vector<ggml_tensor *> nodes;
  11783. std::vector<const char *> names;
  11784. for (int node_idx = prev_node_idx; node_idx < cur_node_idx; ++node_idx) {
  11785. if (ggml_op_is_empty(cgraph->nodes[node_idx]->op)) {
  11786. continue;
  11787. }
  11788. nodes.push_back(cgraph->nodes[node_idx]);
  11789. names.push_back(ctx->query_fusion_names[node_idx]);
  11790. node_idx += ctx->query_fusion_node_count[node_idx];
  11791. }
  11792. prev_node_idx = cur_node_idx;
  11793. ctx->perf_logger->log_timing(nodes, names, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11794. }
  11795. }
  11796. ctx->perf_logger->print_timings();
  11797. }
  11798. if (!ctx->device->support_async) {
  11799. ggml_vk_synchronize(ctx);
  11800. }
  11801. return GGML_STATUS_SUCCESS;
  11802. UNUSED(backend);
  11803. }
  11804. // Sort the graph for improved parallelism.
  11805. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11806. {
  11807. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11808. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11809. if (ctx->device->disable_graph_optimize) {
  11810. return;
  11811. }
  11812. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11813. 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;
  11814. };
  11815. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11816. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11817. if (dst->src[s] == src) {
  11818. return true;
  11819. }
  11820. }
  11821. // implicit dependency if they view the same tensor
  11822. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11823. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11824. if (dst2 == src2) {
  11825. return true;
  11826. }
  11827. return false;
  11828. };
  11829. std::vector<ggml_tensor *> new_order;
  11830. std::vector<bool> used(graph->n_nodes, false);
  11831. std::set<ggml_tensor *> used_node_set;
  11832. int first_unused = 0;
  11833. while (first_unused < graph->n_nodes) {
  11834. std::vector<int> current_set;
  11835. // Check for fusion patterns and avoid reordering them
  11836. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11837. if (start + (int)pattern.size() <= graph->n_nodes) {
  11838. bool is_pattern = true;
  11839. for (size_t j = 0; j < pattern.size(); ++j) {
  11840. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11841. is_pattern = false;
  11842. }
  11843. }
  11844. return is_pattern;
  11845. }
  11846. return false;
  11847. };
  11848. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11849. if (match_pattern(pattern, first_unused)) {
  11850. for (size_t j = 0; j < pattern.size(); ++j) {
  11851. new_order.push_back(graph->nodes[first_unused + j]);
  11852. used_node_set.insert(graph->nodes[first_unused + j]);
  11853. used[first_unused + j] = true;
  11854. }
  11855. while (first_unused < graph->n_nodes && used[first_unused]) {
  11856. first_unused++;
  11857. }
  11858. return true;
  11859. }
  11860. return false;
  11861. };
  11862. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11863. continue;
  11864. }
  11865. if (keep_pattern(topk_moe_sigmoid_norm_bias)) {
  11866. continue;
  11867. }
  11868. if (keep_pattern(topk_moe_early_softmax)) {
  11869. continue;
  11870. }
  11871. if (keep_pattern(topk_moe_late_softmax)) {
  11872. continue;
  11873. }
  11874. // First, grab the next unused node.
  11875. current_set.push_back(first_unused);
  11876. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11877. // haven't already been run. Nodes that have already been run have used[i] set
  11878. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11879. // that we support (e.g. RMS_NORM + MUL).
  11880. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11881. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11882. const int NUM_TO_CHECK = 20;
  11883. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11884. if (used[j]) {
  11885. continue;
  11886. }
  11887. if (is_empty(graph->nodes[j])) {
  11888. continue;
  11889. }
  11890. // Don't pull forward nodes from fusion patterns
  11891. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11892. match_pattern(topk_moe_sigmoid_norm_bias, j) ||
  11893. match_pattern(topk_moe_early_softmax, j) ||
  11894. match_pattern(topk_moe_late_softmax, j)) {
  11895. continue;
  11896. }
  11897. bool ok = true;
  11898. for (int c = first_unused; c < j; ++c) {
  11899. if (!used[c] &&
  11900. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11901. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11902. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11903. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11904. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL) &&
  11905. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_ADD && graph->nodes[j]->op == GGML_OP_ADD)) {
  11906. ok = false;
  11907. break;
  11908. }
  11909. }
  11910. if (ok) {
  11911. current_set.push_back(j);
  11912. int rope_idx = j;
  11913. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11914. if (j > 0 &&
  11915. graph->nodes[j]->op == GGML_OP_MUL &&
  11916. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11917. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11918. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11919. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11920. // Check that other srcs are already valid
  11921. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11922. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11923. rope_idx = k;
  11924. current_set.push_back(rope_idx);
  11925. used[rope_idx] = true;
  11926. break;
  11927. }
  11928. }
  11929. }
  11930. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11931. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11932. int view_idx = -1;
  11933. int set_rows_idx = -1;
  11934. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11935. if (view_idx == -1 &&
  11936. graph->nodes[k]->op == GGML_OP_VIEW &&
  11937. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11938. view_idx = k;
  11939. continue;
  11940. }
  11941. if (view_idx != -1 &&
  11942. set_rows_idx == -1 &&
  11943. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11944. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11945. set_rows_idx = k;
  11946. break;
  11947. }
  11948. }
  11949. if (set_rows_idx != -1) {
  11950. current_set.push_back(view_idx);
  11951. current_set.push_back(set_rows_idx);
  11952. used[view_idx] = true;
  11953. used[set_rows_idx] = true;
  11954. }
  11955. }
  11956. // Look for MUL_MAT_ID + ADD_ID + MUL
  11957. if (j > 0 &&
  11958. graph->nodes[j]->op == GGML_OP_ADD_ID &&
  11959. graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) {
  11960. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11961. if (graph->nodes[k]->op == GGML_OP_MUL &&
  11962. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11963. // src1 must either be weights or already processed
  11964. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11965. current_set.push_back(k);
  11966. used[k] = true;
  11967. break;
  11968. }
  11969. }
  11970. }
  11971. // Look for MUL_MAT + ADD + ADD
  11972. if (j > 0 &&
  11973. graph->nodes[j]->op == GGML_OP_ADD &&
  11974. graph->nodes[j-1]->op == GGML_OP_MUL_MAT) {
  11975. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11976. if (graph->nodes[k]->op == GGML_OP_ADD &&
  11977. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11978. // src1 must either be weights or already processed
  11979. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11980. current_set.push_back(k);
  11981. used[k] = true;
  11982. break;
  11983. }
  11984. }
  11985. }
  11986. }
  11987. }
  11988. // Second pass grabs view nodes.
  11989. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11990. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11991. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11992. if (used[j]) {
  11993. continue;
  11994. }
  11995. if (!is_empty(graph->nodes[j])) {
  11996. continue;
  11997. }
  11998. bool ok = true;
  11999. for (int c = first_unused; c < j; ++c) {
  12000. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  12001. // skip views whose srcs haven't been processed.
  12002. if (!used[c] &&
  12003. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  12004. !c_in_current_set) {
  12005. ok = false;
  12006. break;
  12007. }
  12008. }
  12009. if (ok) {
  12010. current_set.push_back(j);
  12011. }
  12012. }
  12013. }
  12014. // Push the current set into new_order
  12015. for (auto c : current_set) {
  12016. new_order.push_back(graph->nodes[c]);
  12017. used_node_set.insert(graph->nodes[c]);
  12018. used[c] = true;
  12019. }
  12020. while (first_unused < graph->n_nodes && used[first_unused]) {
  12021. first_unused++;
  12022. }
  12023. }
  12024. // Replace the graph with the new order.
  12025. for (int i = 0; i < graph->n_nodes; ++i) {
  12026. graph->nodes[i] = new_order[i];
  12027. }
  12028. }
  12029. static void ggml_backend_vk_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
  12030. VK_LOG_DEBUG("ggml_backend_vk_event_record(backend=" << backend << ", event=" << event << ")");
  12031. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  12032. vk_event *vkev = (vk_event *)event->context;
  12033. vk_context transfer_ctx;
  12034. if (ctx->transfer_ctx.expired()) {
  12035. // Initialize new transfer context
  12036. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  12037. ctx->transfer_ctx = transfer_ctx;
  12038. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  12039. } else {
  12040. transfer_ctx = ctx->transfer_ctx.lock();
  12041. }
  12042. // the backend interface doesn't have an explicit reset, so reset it here
  12043. // before we record the command to set it
  12044. ctx->device->device.resetEvent(vkev->event);
  12045. ctx->device->device.resetFences({ vkev->fence });
  12046. ggml_vk_set_event(transfer_ctx, vkev->event);
  12047. ggml_vk_ctx_end(transfer_ctx);
  12048. ggml_vk_submit(transfer_ctx, {vkev->fence});
  12049. ctx->submit_pending = true;
  12050. ctx->transfer_ctx.reset();
  12051. }
  12052. static void ggml_backend_vk_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
  12053. VK_LOG_DEBUG("ggml_backend_vk_event_wait(backend=" << backend << ", event=" << event << ")");
  12054. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  12055. vk_event *vkev = (vk_event *)event->context;
  12056. vk_context transfer_ctx;
  12057. if (ctx->transfer_ctx.expired()) {
  12058. // Initialize new transfer context
  12059. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  12060. ctx->transfer_ctx = transfer_ctx;
  12061. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  12062. } else {
  12063. transfer_ctx = ctx->transfer_ctx.lock();
  12064. }
  12065. ggml_vk_wait_events(transfer_ctx, {vkev->event});
  12066. ggml_vk_ctx_end(transfer_ctx);
  12067. ctx->transfer_ctx.reset();
  12068. }
  12069. // TODO: enable async and synchronize
  12070. static ggml_backend_i ggml_backend_vk_interface = {
  12071. /* .get_name = */ ggml_backend_vk_name,
  12072. /* .free = */ ggml_backend_vk_free,
  12073. /* .set_tensor_async = */ ggml_backend_vk_set_tensor_async,
  12074. /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async,
  12075. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  12076. /* .synchronize = */ ggml_backend_vk_synchronize,
  12077. /* .graph_plan_create = */ NULL,
  12078. /* .graph_plan_free = */ NULL,
  12079. /* .graph_plan_update = */ NULL,
  12080. /* .graph_plan_compute = */ NULL,
  12081. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  12082. /* .event_record = */ ggml_backend_vk_event_record,
  12083. /* .event_wait = */ ggml_backend_vk_event_wait,
  12084. /* .graph_optimize = */ ggml_vk_graph_optimize,
  12085. };
  12086. static ggml_guid_t ggml_backend_vk_guid() {
  12087. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  12088. return &guid;
  12089. }
  12090. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  12091. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  12092. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  12093. ggml_vk_init(ctx, dev_num);
  12094. ggml_backend_t vk_backend = new ggml_backend {
  12095. /* .guid = */ ggml_backend_vk_guid(),
  12096. /* .iface = */ ggml_backend_vk_interface,
  12097. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  12098. /* .context = */ ctx,
  12099. };
  12100. if (!ctx->device->support_async) {
  12101. vk_backend->iface.get_tensor_async = nullptr;
  12102. }
  12103. return vk_backend;
  12104. }
  12105. bool ggml_backend_is_vk(ggml_backend_t backend) {
  12106. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  12107. }
  12108. int ggml_backend_vk_get_device_count() {
  12109. return ggml_vk_get_device_count();
  12110. }
  12111. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  12112. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  12113. int dev_idx = vk_instance.device_indices[device];
  12114. ggml_vk_get_device_description(dev_idx, description, description_size);
  12115. }
  12116. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  12117. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  12118. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  12119. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  12120. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  12121. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  12122. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  12123. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  12124. if (membudget_supported) {
  12125. memprops.pNext = &budgetprops;
  12126. }
  12127. vkdev.getMemoryProperties2(&memprops);
  12128. *total = 0;
  12129. *free = 0;
  12130. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  12131. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  12132. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  12133. *total += heap.size;
  12134. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  12135. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  12136. } else {
  12137. *free += heap.size;
  12138. }
  12139. }
  12140. }
  12141. }
  12142. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  12143. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  12144. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  12145. vk::PhysicalDeviceProperties2 props = {};
  12146. device.getProperties2(&props);
  12147. return props.properties.deviceType;
  12148. }
  12149. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  12150. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  12151. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  12152. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  12153. bool ext_support = false;
  12154. for (const auto& properties : ext_props) {
  12155. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  12156. ext_support = true;
  12157. break;
  12158. }
  12159. }
  12160. if (!ext_support) {
  12161. return "";
  12162. }
  12163. vk::PhysicalDeviceProperties2 props = {};
  12164. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  12165. props.pNext = &pci_bus_info;
  12166. device.getProperties2(&props);
  12167. const uint32_t pci_domain = pci_bus_info.pciDomain;
  12168. const uint32_t pci_bus = pci_bus_info.pciBus;
  12169. const uint32_t pci_device = pci_bus_info.pciDevice;
  12170. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  12171. char pci_bus_id[16] = {};
  12172. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  12173. return std::string(pci_bus_id);
  12174. }
  12175. //////////////////////////
  12176. struct ggml_backend_vk_device_context {
  12177. size_t device;
  12178. std::string name;
  12179. std::string description;
  12180. bool is_integrated_gpu;
  12181. std::string pci_bus_id;
  12182. };
  12183. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  12184. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12185. return ctx->name.c_str();
  12186. }
  12187. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  12188. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12189. return ctx->description.c_str();
  12190. }
  12191. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  12192. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  12193. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  12194. }
  12195. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  12196. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12197. return ggml_backend_vk_buffer_type(ctx->device);
  12198. }
  12199. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  12200. UNUSED(dev);
  12201. return ggml_backend_vk_host_buffer_type();
  12202. }
  12203. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  12204. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12205. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  12206. }
  12207. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  12208. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12209. props->name = ggml_backend_vk_device_get_name(dev);
  12210. props->description = ggml_backend_vk_device_get_description(dev);
  12211. props->type = ggml_backend_vk_device_get_type(dev);
  12212. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  12213. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  12214. props->caps = {
  12215. /* .async = */ true,
  12216. /* .host_buffer = */ true,
  12217. /* .buffer_from_host_ptr = */ false,
  12218. /* .events = */ true,
  12219. };
  12220. }
  12221. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  12222. UNUSED(params);
  12223. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12224. return ggml_backend_vk_init(ctx->device);
  12225. }
  12226. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12227. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12228. const vk_device& device = ggml_vk_get_device(ctx->device);
  12229. // reject any tensors larger than the max buffer size
  12230. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12231. if (op->src[i] && ggml_nbytes(op->src[i]) > device->max_buffer_size) {
  12232. return false;
  12233. }
  12234. }
  12235. if (ggml_nbytes(op) > device->max_buffer_size) {
  12236. return false;
  12237. }
  12238. switch (op->op) {
  12239. case GGML_OP_UNARY:
  12240. switch (ggml_get_unary_op(op)) {
  12241. case GGML_UNARY_OP_EXP:
  12242. case GGML_UNARY_OP_GELU:
  12243. case GGML_UNARY_OP_GELU_ERF:
  12244. case GGML_UNARY_OP_GELU_QUICK:
  12245. case GGML_UNARY_OP_SILU:
  12246. case GGML_UNARY_OP_RELU:
  12247. case GGML_UNARY_OP_XIELU:
  12248. case GGML_UNARY_OP_NEG:
  12249. case GGML_UNARY_OP_TANH:
  12250. case GGML_UNARY_OP_SIGMOID:
  12251. case GGML_UNARY_OP_HARDSIGMOID:
  12252. case GGML_UNARY_OP_HARDSWISH:
  12253. case GGML_UNARY_OP_ABS:
  12254. case GGML_UNARY_OP_SOFTPLUS:
  12255. case GGML_UNARY_OP_STEP:
  12256. case GGML_UNARY_OP_ROUND:
  12257. case GGML_UNARY_OP_CEIL:
  12258. case GGML_UNARY_OP_FLOOR:
  12259. case GGML_UNARY_OP_TRUNC:
  12260. return ggml_is_contiguous(op->src[0]) &&
  12261. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12262. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  12263. (op->src[0]->type == op->type);
  12264. default:
  12265. return false;
  12266. }
  12267. case GGML_OP_GLU:
  12268. switch (ggml_get_glu_op(op)) {
  12269. case GGML_GLU_OP_GEGLU:
  12270. case GGML_GLU_OP_REGLU:
  12271. case GGML_GLU_OP_SWIGLU:
  12272. case GGML_GLU_OP_SWIGLU_OAI:
  12273. case GGML_GLU_OP_GEGLU_ERF:
  12274. case GGML_GLU_OP_GEGLU_QUICK:
  12275. return ggml_is_contiguous(op->src[0]) &&
  12276. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12277. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  12278. (op->src[0]->type == op->type);
  12279. default:
  12280. return false;
  12281. }
  12282. case GGML_OP_MUL_MAT:
  12283. case GGML_OP_MUL_MAT_ID:
  12284. {
  12285. ggml_type src0_type = op->src[0]->type;
  12286. if (op->op == GGML_OP_MUL_MAT_ID) {
  12287. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  12288. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  12289. return false;
  12290. }
  12291. }
  12292. switch (src0_type) {
  12293. case GGML_TYPE_F32:
  12294. case GGML_TYPE_F16:
  12295. case GGML_TYPE_BF16:
  12296. case GGML_TYPE_Q4_0:
  12297. case GGML_TYPE_Q4_1:
  12298. case GGML_TYPE_Q5_0:
  12299. case GGML_TYPE_Q5_1:
  12300. case GGML_TYPE_Q8_0:
  12301. case GGML_TYPE_Q2_K:
  12302. case GGML_TYPE_Q3_K:
  12303. case GGML_TYPE_Q4_K:
  12304. case GGML_TYPE_Q5_K:
  12305. case GGML_TYPE_Q6_K:
  12306. case GGML_TYPE_IQ1_S:
  12307. case GGML_TYPE_IQ1_M:
  12308. case GGML_TYPE_IQ2_XXS:
  12309. case GGML_TYPE_IQ2_XS:
  12310. case GGML_TYPE_IQ2_S:
  12311. case GGML_TYPE_IQ3_XXS:
  12312. case GGML_TYPE_IQ3_S:
  12313. case GGML_TYPE_IQ4_XS:
  12314. case GGML_TYPE_IQ4_NL:
  12315. case GGML_TYPE_MXFP4:
  12316. break;
  12317. default:
  12318. return false;
  12319. }
  12320. struct ggml_tensor * a;
  12321. struct ggml_tensor * b;
  12322. if (op->op == GGML_OP_MUL_MAT) {
  12323. a = op->src[0];
  12324. b = op->src[1];
  12325. } else {
  12326. a = op->src[2];
  12327. b = op->src[1];
  12328. }
  12329. if (a->ne[3] != b->ne[3]) {
  12330. return false;
  12331. }
  12332. 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) ||
  12333. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  12334. return false;
  12335. }
  12336. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  12337. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  12338. // So don't support this combination for now.
  12339. return false;
  12340. }
  12341. return true;
  12342. }
  12343. case GGML_OP_FLASH_ATTN_EXT:
  12344. {
  12345. bool coopmat2 = device->coopmat2;
  12346. uint32_t HSK = op->src[1]->ne[0];
  12347. uint32_t HSV = op->src[2]->ne[0];
  12348. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  12349. return false;
  12350. }
  12351. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  12352. return false;
  12353. }
  12354. if (op->src[0]->type != GGML_TYPE_F32) {
  12355. return false;
  12356. }
  12357. if (op->type != GGML_TYPE_F32) {
  12358. return false;
  12359. }
  12360. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  12361. return false;
  12362. }
  12363. // It's straightforward to support different K/V dequant, but would
  12364. // significantly increase the number of pipelines
  12365. if (op->src[1]->type != op->src[2]->type) {
  12366. return false;
  12367. }
  12368. switch (op->src[1]->type) {
  12369. case GGML_TYPE_F16:
  12370. case GGML_TYPE_F32:
  12371. case GGML_TYPE_Q4_0:
  12372. case GGML_TYPE_Q8_0:
  12373. // supported in scalar and coopmat2 paths
  12374. break;
  12375. case GGML_TYPE_Q4_1:
  12376. case GGML_TYPE_Q5_0:
  12377. case GGML_TYPE_Q5_1:
  12378. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  12379. //case GGML_TYPE_Q2_K:
  12380. //case GGML_TYPE_Q3_K:
  12381. //case GGML_TYPE_Q4_K:
  12382. //case GGML_TYPE_Q5_K:
  12383. //case GGML_TYPE_Q6_K:
  12384. //case GGML_TYPE_IQ1_S:
  12385. //case GGML_TYPE_IQ1_M:
  12386. //case GGML_TYPE_IQ2_XXS:
  12387. //case GGML_TYPE_IQ2_XS:
  12388. //case GGML_TYPE_IQ2_S:
  12389. //case GGML_TYPE_IQ3_XXS:
  12390. //case GGML_TYPE_IQ3_S:
  12391. //case GGML_TYPE_IQ4_XS:
  12392. case GGML_TYPE_IQ4_NL:
  12393. // currently supported only in coopmat2 path
  12394. if (!coopmat2) {
  12395. return false;
  12396. }
  12397. break;
  12398. default:
  12399. return false;
  12400. }
  12401. if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) {
  12402. // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll
  12403. return false;
  12404. }
  12405. return true;
  12406. }
  12407. case GGML_OP_GET_ROWS:
  12408. {
  12409. switch (op->src[0]->type) {
  12410. case GGML_TYPE_F32:
  12411. case GGML_TYPE_F16:
  12412. case GGML_TYPE_BF16:
  12413. case GGML_TYPE_Q4_0:
  12414. case GGML_TYPE_Q4_1:
  12415. case GGML_TYPE_Q5_0:
  12416. case GGML_TYPE_Q5_1:
  12417. case GGML_TYPE_Q8_0:
  12418. case GGML_TYPE_Q2_K:
  12419. case GGML_TYPE_Q3_K:
  12420. case GGML_TYPE_Q4_K:
  12421. case GGML_TYPE_Q5_K:
  12422. case GGML_TYPE_Q6_K:
  12423. case GGML_TYPE_IQ1_S:
  12424. case GGML_TYPE_IQ1_M:
  12425. case GGML_TYPE_IQ2_XXS:
  12426. case GGML_TYPE_IQ2_XS:
  12427. case GGML_TYPE_IQ2_S:
  12428. case GGML_TYPE_IQ3_XXS:
  12429. case GGML_TYPE_IQ3_S:
  12430. case GGML_TYPE_IQ4_XS:
  12431. case GGML_TYPE_IQ4_NL:
  12432. case GGML_TYPE_MXFP4:
  12433. case GGML_TYPE_I32:
  12434. return true;
  12435. default:
  12436. return false;
  12437. }
  12438. }
  12439. case GGML_OP_SET_ROWS:
  12440. {
  12441. switch (op->type) {
  12442. case GGML_TYPE_F32:
  12443. case GGML_TYPE_F16:
  12444. case GGML_TYPE_BF16:
  12445. case GGML_TYPE_Q4_0:
  12446. case GGML_TYPE_Q4_1:
  12447. case GGML_TYPE_Q5_0:
  12448. case GGML_TYPE_Q5_1:
  12449. case GGML_TYPE_Q8_0:
  12450. case GGML_TYPE_IQ4_NL:
  12451. return true;
  12452. default:
  12453. return false;
  12454. }
  12455. }
  12456. case GGML_OP_CONT:
  12457. case GGML_OP_CPY:
  12458. case GGML_OP_DUP:
  12459. {
  12460. ggml_type src0_type = op->src[0]->type;
  12461. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  12462. if (src0_type == GGML_TYPE_F32) {
  12463. switch (src1_type) {
  12464. case GGML_TYPE_F32:
  12465. case GGML_TYPE_F16:
  12466. case GGML_TYPE_BF16:
  12467. case GGML_TYPE_Q4_0:
  12468. case GGML_TYPE_Q4_1:
  12469. case GGML_TYPE_Q5_0:
  12470. case GGML_TYPE_Q5_1:
  12471. case GGML_TYPE_Q8_0:
  12472. case GGML_TYPE_IQ4_NL:
  12473. return true;
  12474. default:
  12475. break;
  12476. }
  12477. }
  12478. if (src1_type == GGML_TYPE_F32) {
  12479. switch (src0_type) {
  12480. case GGML_TYPE_F16:
  12481. case GGML_TYPE_Q4_0:
  12482. case GGML_TYPE_Q4_1:
  12483. case GGML_TYPE_Q5_0:
  12484. case GGML_TYPE_Q5_1:
  12485. case GGML_TYPE_Q8_0:
  12486. case GGML_TYPE_IQ4_NL:
  12487. return true;
  12488. default:
  12489. break;
  12490. }
  12491. }
  12492. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  12493. return true;
  12494. }
  12495. if (
  12496. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  12497. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  12498. ) {
  12499. return true;
  12500. }
  12501. // We can handle copying from a type to the same type if it's
  12502. // either not quantized or is quantized and contiguous.
  12503. // We use f16 or f32 shaders to do the copy,
  12504. // so the type/block size must be a multiple of 4.
  12505. if (src0_type == src1_type &&
  12506. (!ggml_is_quantized(src0_type) || (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op))) &&
  12507. (ggml_type_size(src0_type) % 2) == 0) {
  12508. return true;
  12509. }
  12510. return false;
  12511. }
  12512. case GGML_OP_REPEAT:
  12513. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  12514. case GGML_OP_REPEAT_BACK:
  12515. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  12516. case GGML_OP_ROPE:
  12517. case GGML_OP_ROPE_BACK:
  12518. case GGML_OP_NONE:
  12519. case GGML_OP_RESHAPE:
  12520. case GGML_OP_VIEW:
  12521. case GGML_OP_PERMUTE:
  12522. case GGML_OP_TRANSPOSE:
  12523. case GGML_OP_RMS_NORM:
  12524. return true;
  12525. case GGML_OP_NORM:
  12526. case GGML_OP_GROUP_NORM:
  12527. case GGML_OP_L2_NORM:
  12528. return ggml_is_contiguous(op->src[0]);
  12529. case GGML_OP_ADD:
  12530. case GGML_OP_SUB:
  12531. case GGML_OP_MUL:
  12532. case GGML_OP_DIV:
  12533. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12534. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  12535. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12536. case GGML_OP_ADD_ID:
  12537. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  12538. op->type == GGML_TYPE_F32;
  12539. case GGML_OP_SILU_BACK:
  12540. case GGML_OP_RMS_NORM_BACK:
  12541. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12542. case GGML_OP_SQR:
  12543. case GGML_OP_SQRT:
  12544. case GGML_OP_SIN:
  12545. case GGML_OP_COS:
  12546. case GGML_OP_CLAMP:
  12547. return op->src[0]->type == GGML_TYPE_F32;
  12548. case GGML_OP_LEAKY_RELU:
  12549. case GGML_OP_OPT_STEP_ADAMW:
  12550. case GGML_OP_OPT_STEP_SGD:
  12551. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12552. case GGML_OP_LOG:
  12553. case GGML_OP_TRI:
  12554. case GGML_OP_DIAG:
  12555. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12556. op->type == op->src[0]->type;
  12557. case GGML_OP_ARGSORT:
  12558. {
  12559. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12560. return false;
  12561. }
  12562. // pipeline_argsort_large_f32 requires vulkan memory model.
  12563. if (device->vulkan_memory_model) {
  12564. return true;
  12565. } else {
  12566. return op->ne[0] <= (1 << device->max_workgroup_size_log2);
  12567. }
  12568. }
  12569. case GGML_OP_TOP_K:
  12570. {
  12571. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12572. return false;
  12573. }
  12574. // We could potentially support larger, using argsort to sort the
  12575. // whole thing. Not clear if this is needed.
  12576. uint32_t min_pipeline = (uint32_t)log2f(float(op->ne[0])) + 1;
  12577. if (min_pipeline >= num_topk_pipelines ||
  12578. !device->pipeline_topk_f32[min_pipeline]) {
  12579. return false;
  12580. }
  12581. }
  12582. return true;
  12583. case GGML_OP_UPSCALE:
  12584. if (op->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS) {
  12585. if ((op->op_params[0] & 0xFF) != GGML_SCALE_MODE_BILINEAR) {
  12586. return false;
  12587. }
  12588. }
  12589. return op->src[0]->type == GGML_TYPE_F32;
  12590. case GGML_OP_ACC:
  12591. return op->src[0]->type == GGML_TYPE_F32;
  12592. case GGML_OP_CONCAT:
  12593. return ggml_type_size(op->src[0]->type) == ggml_type_size(GGML_TYPE_F32);
  12594. case GGML_OP_ADD1:
  12595. return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32)
  12596. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32)
  12597. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16);
  12598. case GGML_OP_ARANGE:
  12599. case GGML_OP_FILL:
  12600. return op->type == GGML_TYPE_F32;
  12601. case GGML_OP_SCALE:
  12602. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12603. case GGML_OP_PAD:
  12604. case GGML_OP_ROLL:
  12605. return op->src[0]->type == GGML_TYPE_F32;
  12606. case GGML_OP_DIAG_MASK_INF:
  12607. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12608. case GGML_OP_SOFT_MAX:
  12609. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12610. && (!op->src[1] || (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16));
  12611. case GGML_OP_SOFT_MAX_BACK:
  12612. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12613. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32;
  12614. case GGML_OP_SUM:
  12615. case GGML_OP_SUM_ROWS:
  12616. case GGML_OP_MEAN:
  12617. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12618. case GGML_OP_CUMSUM:
  12619. {
  12620. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  12621. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12622. }
  12623. return false;
  12624. }
  12625. case GGML_OP_SOLVE_TRI:
  12626. {
  12627. if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32) {
  12628. return false;
  12629. }
  12630. const uint32_t N = op->src[0]->ne[0];
  12631. const uint32_t K = op->src[1]->ne[0];
  12632. // K dimension limited to workgroup size
  12633. if (K > 1u << device->max_workgroup_size_log2) {
  12634. return false;
  12635. }
  12636. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((N + K) * sizeof(float));
  12637. if (batch_N == 0) {
  12638. return false;
  12639. }
  12640. return true;
  12641. }
  12642. case GGML_OP_ARGMAX:
  12643. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12644. case GGML_OP_COUNT_EQUAL:
  12645. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_I32
  12646. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_I32;
  12647. case GGML_OP_IM2COL:
  12648. return ggml_is_contiguous(op->src[1])
  12649. && op->src[1]->type == GGML_TYPE_F32
  12650. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12651. case GGML_OP_IM2COL_3D:
  12652. return op->src[1]->type == GGML_TYPE_F32
  12653. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12654. case GGML_OP_TIMESTEP_EMBEDDING:
  12655. return op->src[0]->type == GGML_TYPE_F32;
  12656. case GGML_OP_CONV_2D_DW:
  12657. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16)
  12658. && op->src[1]->type == GGML_TYPE_F32;
  12659. case GGML_OP_POOL_2D:
  12660. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12661. case GGML_OP_RWKV_WKV6:
  12662. case GGML_OP_RWKV_WKV7:
  12663. return true; // all inputs are contiguous, see ggml.c
  12664. case GGML_OP_SSM_SCAN:
  12665. {
  12666. for (int i = 0; i < 6; i++) {
  12667. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  12668. return false;
  12669. }
  12670. }
  12671. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  12672. return false;
  12673. }
  12674. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  12675. return false;
  12676. }
  12677. const uint32_t d_state = op->src[0]->ne[0];
  12678. const uint32_t head_dim = op->src[0]->ne[1];
  12679. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  12680. if (!is_mamba2) {
  12681. return false;
  12682. }
  12683. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  12684. return false;
  12685. }
  12686. const uint32_t SPLIT_H = 16;
  12687. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  12688. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  12689. return false;
  12690. }
  12691. return true;
  12692. }
  12693. case GGML_OP_SSM_CONV:
  12694. return op->src[0]->type == GGML_TYPE_F32;
  12695. case GGML_OP_CONV_TRANSPOSE_1D:
  12696. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  12697. case GGML_OP_CONV_2D:
  12698. case GGML_OP_CONV_TRANSPOSE_2D:
  12699. {
  12700. // Channel-contiguous format is not supported yet.
  12701. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12702. op->src[1]->type == GGML_TYPE_F32 &&
  12703. op->type == GGML_TYPE_F32 &&
  12704. ggml_is_contiguous(op->src[0]) &&
  12705. ggml_is_contiguous(op->src[1]) &&
  12706. ggml_is_contiguous(op));
  12707. }
  12708. default:
  12709. return false;
  12710. }
  12711. UNUSED(dev);
  12712. }
  12713. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  12714. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  12715. return false;
  12716. }
  12717. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12718. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  12719. return buft_ctx->device->idx == ctx->device;
  12720. }
  12721. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12722. const int min_batch_size = 32;
  12723. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  12724. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  12725. UNUSED(dev);
  12726. }
  12727. static ggml_backend_event_t ggml_backend_vk_device_event_new(ggml_backend_dev_t dev) {
  12728. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12729. auto device = ggml_vk_get_device(ctx->device);
  12730. vk_event *vkev = new vk_event;
  12731. if (!vkev) {
  12732. return nullptr;
  12733. }
  12734. // The event/fence is expected to initially be in the signaled state.
  12735. vkev->event = device->device.createEvent({});
  12736. vkev->fence = device->device.createFence({vk::FenceCreateFlagBits::eSignaled});
  12737. device->device.setEvent(vkev->event);
  12738. return new ggml_backend_event {
  12739. /* .device = */ dev,
  12740. /* .context = */ vkev,
  12741. };
  12742. }
  12743. static void ggml_backend_vk_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  12744. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12745. auto device = ggml_vk_get_device(ctx->device);
  12746. vk_event *vkev = (vk_event *)event->context;
  12747. device->device.destroyFence(vkev->fence);
  12748. device->device.destroyEvent(vkev->event);
  12749. delete vkev;
  12750. delete event;
  12751. }
  12752. static void ggml_backend_vk_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  12753. VK_LOG_DEBUG("ggml_backend_vk_device_event_synchronize(backend=" << dev << ", event=" << event << ")");
  12754. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12755. auto device = ggml_vk_get_device(ctx->device);
  12756. vk_event *vkev = (vk_event *)event->context;
  12757. VK_CHECK(device->device.waitForFences({ vkev->fence }, true, UINT64_MAX), "event_synchronize");
  12758. }
  12759. static vk_buffer ggml_vk_buffer_from_host_ptr(vk_device & device, void * ptr, size_t size) {
  12760. if (!device->external_memory_host) {
  12761. return {};
  12762. }
  12763. uintptr_t uptr = reinterpret_cast<uintptr_t>(ptr);
  12764. if (uptr & (device->min_imported_host_pointer_alignment - 1)) {
  12765. return {};
  12766. }
  12767. if (size & (device->min_imported_host_pointer_alignment - 1)) {
  12768. return {};
  12769. }
  12770. const vk::MemoryPropertyFlags property_flags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached;
  12771. vk_buffer buf {};
  12772. try {
  12773. buf = ggml_vk_create_buffer(device, size, { property_flags }, ptr);
  12774. } catch (vk::SystemError& e) {
  12775. GGML_LOG_WARN("ggml_vulkan: Failed ggml_vk_create_buffer (%s)\n", e.what());
  12776. }
  12777. return buf;
  12778. }
  12779. static ggml_backend_buffer_t ggml_backend_vk_device_buffer_from_host_ptr(ggml_backend_dev_t dev, void * ptr, size_t size, size_t max_tensor_size) {
  12780. VK_LOG_DEBUG("ggml_backend_vk_device_buffer_from_host_ptr(backend=" << dev << ", ptr=" << ptr << ", size=" << size << ")");
  12781. GGML_UNUSED(max_tensor_size);
  12782. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12783. auto device = ggml_vk_get_device(ctx->device);
  12784. vk_buffer buf = ggml_vk_buffer_from_host_ptr(device, ptr, size);
  12785. if (!buf) {
  12786. return {};
  12787. }
  12788. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(device, std::move(buf), device->name);
  12789. ggml_backend_buffer_t ret = ggml_backend_buffer_init(ggml_backend_vk_device_get_buffer_type(dev), ggml_backend_vk_buffer_interface, bufctx, size);
  12790. return ret;
  12791. }
  12792. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  12793. /* .get_name = */ ggml_backend_vk_device_get_name,
  12794. /* .get_description = */ ggml_backend_vk_device_get_description,
  12795. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  12796. /* .get_type = */ ggml_backend_vk_device_get_type,
  12797. /* .get_props = */ ggml_backend_vk_device_get_props,
  12798. /* .init_backend = */ ggml_backend_vk_device_init,
  12799. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  12800. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  12801. /* .buffer_from_host_ptr = */ ggml_backend_vk_device_buffer_from_host_ptr,
  12802. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  12803. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  12804. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  12805. /* .event_new = */ ggml_backend_vk_device_event_new,
  12806. /* .event_free = */ ggml_backend_vk_device_event_free,
  12807. /* .event_synchronize = */ ggml_backend_vk_device_event_synchronize,
  12808. };
  12809. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  12810. UNUSED(reg);
  12811. return GGML_VK_NAME;
  12812. }
  12813. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  12814. UNUSED(reg);
  12815. return ggml_backend_vk_get_device_count();
  12816. }
  12817. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  12818. static std::vector<ggml_backend_dev_t> devices;
  12819. static bool initialized = false;
  12820. {
  12821. static std::mutex mutex;
  12822. std::lock_guard<std::mutex> lock(mutex);
  12823. if (!initialized) {
  12824. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  12825. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  12826. char desc[256];
  12827. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  12828. ctx->device = i;
  12829. ctx->name = GGML_VK_NAME + std::to_string(i);
  12830. ctx->description = desc;
  12831. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  12832. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  12833. devices.push_back(new ggml_backend_device {
  12834. /* .iface = */ ggml_backend_vk_device_i,
  12835. /* .reg = */ reg,
  12836. /* .context = */ ctx,
  12837. });
  12838. }
  12839. initialized = true;
  12840. }
  12841. }
  12842. GGML_ASSERT(device < devices.size());
  12843. return devices[device];
  12844. }
  12845. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  12846. /* .get_name = */ ggml_backend_vk_reg_get_name,
  12847. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  12848. /* .get_device = */ ggml_backend_vk_reg_get_device,
  12849. /* .get_proc_address = */ NULL,
  12850. };
  12851. ggml_backend_reg_t ggml_backend_vk_reg() {
  12852. static ggml_backend_reg reg = {
  12853. /* .api_version = */ GGML_BACKEND_API_VERSION,
  12854. /* .iface = */ ggml_backend_vk_reg_i,
  12855. /* .context = */ nullptr,
  12856. };
  12857. try {
  12858. ggml_vk_instance_init();
  12859. return &reg;
  12860. } catch (const vk::SystemError& e) {
  12861. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  12862. return nullptr;
  12863. } catch (const std::exception &e) {
  12864. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  12865. return nullptr;
  12866. } catch (...) {
  12867. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  12868. return nullptr;
  12869. }
  12870. }
  12871. // Extension availability
  12872. static bool ggml_vk_instance_layer_settings_available() {
  12873. #ifdef GGML_VULKAN_VALIDATE
  12874. // Check if validation layer provides the extension
  12875. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  12876. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  12877. if (layer_name == layer.layerName.data()) {
  12878. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  12879. if (strcmp("VK_EXT_layer_settings", ext.extensionName.data()) == 0) {
  12880. return true;
  12881. }
  12882. }
  12883. }
  12884. }
  12885. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_layer_settings not found." << std::endl;
  12886. #endif
  12887. return false;
  12888. }
  12889. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  12890. #ifdef __APPLE__
  12891. // Check for portability enumeration extension for MoltenVK support
  12892. for (const auto& properties : instance_extensions) {
  12893. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  12894. return true;
  12895. }
  12896. }
  12897. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  12898. #endif
  12899. return false;
  12900. UNUSED(instance_extensions);
  12901. }
  12902. // Extension availability
  12903. static bool ggml_vk_instance_debug_utils_ext_available(
  12904. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  12905. // Check for portability enumeration extension for MoltenVK support
  12906. for (const auto & properties : instance_extensions) {
  12907. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  12908. return true;
  12909. }
  12910. }
  12911. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  12912. return false;
  12913. UNUSED(instance_extensions);
  12914. }
  12915. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  12916. VkPhysicalDeviceFeatures2 device_features2;
  12917. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  12918. VkPhysicalDeviceVulkan11Features vk11_features;
  12919. vk11_features.pNext = nullptr;
  12920. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  12921. device_features2.pNext = &vk11_features;
  12922. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  12923. return vk11_features.storageBuffer16BitAccess;
  12924. }
  12925. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  12926. switch (props.vendorID) {
  12927. case VK_VENDOR_ID_INTEL:
  12928. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  12929. // while some older hardware (ex. Arc A770) has performance regressions
  12930. return arch == vk_device_architecture::INTEL_XE2;
  12931. case VK_VENDOR_ID_AMD:
  12932. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  12933. // Workaround for AMD proprietary driver reporting support on all GPUs
  12934. return arch == vk_device_architecture::AMD_RDNA3;
  12935. }
  12936. return true;
  12937. default:
  12938. return true;
  12939. }
  12940. }
  12941. // checks
  12942. #ifdef GGML_VULKAN_CHECK_RESULTS
  12943. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  12944. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  12945. return;
  12946. }
  12947. for (int j = 0; j < level; j++) {
  12948. std::cerr << " ";
  12949. }
  12950. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  12951. done.push_back(tensor);
  12952. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12953. if (tensor->src[i] != nullptr) {
  12954. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  12955. }
  12956. }
  12957. }
  12958. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  12959. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  12960. return;
  12961. }
  12962. i0 = std::max(i0, 5);
  12963. i1 = std::max(i1, 5);
  12964. i2 = std::max(i2, 0);
  12965. i3 = std::max(i3, 0);
  12966. fprintf(stderr, " ");
  12967. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12968. fprintf(stderr, "%7d ", idx1);
  12969. }
  12970. fprintf(stderr, "\n");
  12971. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12972. fprintf(stderr, "%7d: ", idx0);
  12973. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12974. 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]) {
  12975. float val;
  12976. if (tensor->type == GGML_TYPE_F32) {
  12977. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12978. } else if (tensor->type == GGML_TYPE_F16) {
  12979. 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]));
  12980. } else if (tensor->type == GGML_TYPE_I32) {
  12981. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12982. } else {
  12983. GGML_ABORT("fatal error");
  12984. }
  12985. fprintf(stderr, "% 7.2f ", val);
  12986. } else {
  12987. fprintf(stderr, " ");
  12988. }
  12989. }
  12990. fprintf(stderr, "\n");
  12991. }
  12992. }
  12993. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  12994. void * tensor_data = tensor->data;
  12995. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  12996. if (is_gpu) {
  12997. const size_t tensor_size = ggml_nbytes(tensor);
  12998. tensor_data = malloc(tensor_size);
  12999. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  13000. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  13001. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  13002. }
  13003. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  13004. 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;
  13005. if (tensor->src[0] != nullptr) {
  13006. 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;
  13007. }
  13008. if (tensor->src[1] != nullptr) {
  13009. 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;
  13010. }
  13011. std::cerr << std::endl << "Result:" << std::endl;
  13012. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13013. std::cerr << std::endl;
  13014. std::vector<const ggml_tensor *> done;
  13015. ggml_vk_print_graph_origin(tensor, done);
  13016. if (is_gpu) {
  13017. free(tensor_data);
  13018. }
  13019. }
  13020. void * comp_result;
  13021. size_t comp_size;
  13022. size_t comp_nb[GGML_MAX_DIMS];
  13023. size_t check_counter = 0;
  13024. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  13025. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  13026. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  13027. return;
  13028. }
  13029. check_counter++;
  13030. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  13031. return;
  13032. }
  13033. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  13034. struct ggml_init_params iparams = {
  13035. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  13036. /*.mem_buffer =*/ NULL,
  13037. /*.no_alloc =*/ false,
  13038. };
  13039. struct ggml_context * ggml_ctx = ggml_init(iparams);
  13040. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  13041. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  13042. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  13043. std::vector<void *> cloned_mallocs;
  13044. struct ggml_tensor * tensor_clone = nullptr;
  13045. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  13046. tensor = cgraph->nodes[tensor_idx + f];
  13047. for (int i = 0; i < GGML_MAX_SRC; i++) {
  13048. ggml_tensor * srci = tensor->src[i];
  13049. if (srci == nullptr) {
  13050. continue;
  13051. }
  13052. // If a src tensor has been cloned, use that one
  13053. auto it = cloned_tensors.find(srci);
  13054. if (it != cloned_tensors.end()) {
  13055. src_clone[i] = it->second;
  13056. continue;
  13057. }
  13058. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  13059. size_t srci_size = ggml_nbytes(srci);
  13060. src_clone[i] = srci_clone;
  13061. void *src_buffer = malloc(srci_size);
  13062. cloned_mallocs.push_back(src_buffer);
  13063. srci_clone->data = src_buffer;
  13064. if (ggml_backend_buffer_is_host(srci->buffer)) {
  13065. memcpy(srci_clone->data, srci->data, srci_size);
  13066. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13067. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  13068. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  13069. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  13070. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  13071. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  13072. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  13073. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  13074. const int idx = i3*srci->ne[2] + i2;
  13075. 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]);
  13076. }
  13077. }
  13078. srci_clone->nb[0] = srci->nb[0];
  13079. srci_clone->nb[1] = srci->nb[1];
  13080. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  13081. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  13082. }
  13083. } else {
  13084. if (offset + srci_size >= buffer_gpu->size) {
  13085. srci_size = buffer_gpu->size - offset;
  13086. }
  13087. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  13088. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13089. }
  13090. } else {
  13091. GGML_ABORT("fatal error");
  13092. }
  13093. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13094. ggml_vk_print_tensor(srci, srci_name[i]);
  13095. }
  13096. }
  13097. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  13098. const float * params = (const float *)tensor->op_params;
  13099. 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]);
  13100. if (src_clone[4]) {
  13101. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  13102. }
  13103. } else if (tensor->op == GGML_OP_MUL_MAT) {
  13104. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  13105. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  13106. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  13107. } else if (tensor->op == GGML_OP_SUB) {
  13108. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  13109. } else if (tensor->op == GGML_OP_MUL) {
  13110. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  13111. } else if (tensor->op == GGML_OP_DIV) {
  13112. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  13113. } else if (tensor->op == GGML_OP_CONCAT) {
  13114. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  13115. } else if (tensor->op == GGML_OP_UPSCALE) {
  13116. 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]);
  13117. } else if (tensor->op == GGML_OP_SCALE) {
  13118. const float * params = (const float *)tensor->op_params;
  13119. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  13120. } else if (tensor->op == GGML_OP_ADD1) {
  13121. tensor_clone = ggml_add1(ggml_ctx, src_clone[0], src_clone[1]);
  13122. } else if (tensor->op == GGML_OP_ARANGE) {
  13123. const float start = ggml_get_op_params_f32(tensor, 0);
  13124. const float stop = ggml_get_op_params_f32(tensor, 1);
  13125. const float step = ggml_get_op_params_f32(tensor, 2);
  13126. tensor_clone = ggml_arange(ggml_ctx, start, stop, step);
  13127. } else if (tensor->op == GGML_OP_FILL) {
  13128. const float value = ggml_get_op_params_f32(tensor, 0);
  13129. tensor_clone = ggml_fill(ggml_ctx, tensor_clone, value);
  13130. } else if (tensor->op == GGML_OP_SQR) {
  13131. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  13132. } else if (tensor->op == GGML_OP_SQRT) {
  13133. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  13134. } else if (tensor->op == GGML_OP_SIN) {
  13135. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  13136. } else if (tensor->op == GGML_OP_COS) {
  13137. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  13138. } else if (tensor->op == GGML_OP_LOG) {
  13139. tensor_clone = ggml_log(ggml_ctx, src_clone[0]);
  13140. } else if (tensor->op == GGML_OP_TRI) {
  13141. tensor_clone = ggml_tri(ggml_ctx, src_clone[0], (ggml_tri_type)ggml_get_op_params_i32(tensor, 0));
  13142. } else if (tensor->op == GGML_OP_DIAG) {
  13143. tensor_clone = ggml_diag(ggml_ctx, src_clone[0]);
  13144. } else if (tensor->op == GGML_OP_CLAMP) {
  13145. const float * params = (const float *)tensor->op_params;
  13146. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  13147. } else if (tensor->op == GGML_OP_PAD) {
  13148. 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],
  13149. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  13150. } else if (tensor->op == GGML_OP_REPEAT) {
  13151. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  13152. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  13153. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  13154. } else if (tensor->op == GGML_OP_ADD) {
  13155. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  13156. } else if (tensor->op == GGML_OP_ACC) {
  13157. 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]);
  13158. } else if (tensor->op == GGML_OP_NORM) {
  13159. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  13160. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  13161. const float * float_params = (const float *)tensor->op_params;
  13162. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  13163. } else if (tensor->op == GGML_OP_RMS_NORM) {
  13164. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  13165. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  13166. const float eps = ((float *) tensor->op_params)[0];
  13167. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  13168. } else if (tensor->op == GGML_OP_SILU_BACK) {
  13169. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  13170. } else if (tensor->op == GGML_OP_L2_NORM) {
  13171. const float eps = ((float *) tensor->op_params)[0];
  13172. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  13173. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  13174. if (tensor->src[1] != nullptr) {
  13175. const float * params = (const float *)tensor->op_params;
  13176. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  13177. } else {
  13178. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  13179. }
  13180. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  13181. 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]);
  13182. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  13183. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  13184. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  13185. const int n_dims = ((int32_t *) tensor->op_params)[1];
  13186. const int mode = ((int32_t *) tensor->op_params)[2];
  13187. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  13188. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  13189. const float freq_base = ((float *) tensor->op_params)[5];
  13190. const float freq_scale = ((float *) tensor->op_params)[6];
  13191. const float ext_factor = ((float *) tensor->op_params)[7];
  13192. const float attn_factor = ((float *) tensor->op_params)[8];
  13193. const float beta_fast = ((float *) tensor->op_params)[9];
  13194. const float beta_slow = ((float *) tensor->op_params)[10];
  13195. if (mode & GGML_ROPE_TYPE_MROPE) {
  13196. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  13197. if (tensor->op == GGML_OP_ROPE) {
  13198. 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);
  13199. } else {
  13200. 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);
  13201. }
  13202. } else {
  13203. if (tensor->op == GGML_OP_ROPE) {
  13204. 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);
  13205. } else {
  13206. 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);
  13207. }
  13208. }
  13209. } else if (tensor->op == GGML_OP_UNARY) {
  13210. switch (ggml_get_unary_op(tensor)) {
  13211. case GGML_UNARY_OP_EXP:
  13212. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  13213. break;
  13214. case GGML_UNARY_OP_SILU:
  13215. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  13216. break;
  13217. case GGML_UNARY_OP_GELU:
  13218. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  13219. break;
  13220. case GGML_UNARY_OP_GELU_ERF:
  13221. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  13222. break;
  13223. case GGML_UNARY_OP_GELU_QUICK:
  13224. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  13225. break;
  13226. case GGML_UNARY_OP_RELU:
  13227. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  13228. break;
  13229. case GGML_UNARY_OP_XIELU:
  13230. tensor_clone = ggml_xielu(ggml_ctx, src_clone[0], 0, 0, 0, 0);
  13231. ggml_set_op_params_f32(tensor_clone, 1, ggml_get_op_params_f32(tensor, 1));
  13232. ggml_set_op_params_f32(tensor_clone, 2, ggml_get_op_params_f32(tensor, 2));
  13233. ggml_set_op_params_f32(tensor_clone, 3, ggml_get_op_params_f32(tensor, 3));
  13234. ggml_set_op_params_f32(tensor_clone, 4, ggml_get_op_params_f32(tensor, 4));
  13235. break;
  13236. case GGML_UNARY_OP_NEG:
  13237. tensor_clone = ggml_neg(ggml_ctx, src_clone[0]);
  13238. break;
  13239. case GGML_UNARY_OP_TANH:
  13240. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  13241. break;
  13242. case GGML_UNARY_OP_SIGMOID:
  13243. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  13244. break;
  13245. case GGML_UNARY_OP_HARDSIGMOID:
  13246. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  13247. break;
  13248. case GGML_UNARY_OP_HARDSWISH:
  13249. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  13250. break;
  13251. case GGML_UNARY_OP_ABS:
  13252. tensor_clone = ggml_abs(ggml_ctx, src_clone[0]);
  13253. break;
  13254. case GGML_UNARY_OP_SOFTPLUS:
  13255. tensor_clone = ggml_softplus(ggml_ctx, src_clone[0]);
  13256. break;
  13257. case GGML_UNARY_OP_STEP:
  13258. tensor_clone = ggml_step(ggml_ctx, src_clone[0]);
  13259. break;
  13260. case GGML_UNARY_OP_ROUND:
  13261. tensor_clone = ggml_round(ggml_ctx, src_clone[0]);
  13262. break;
  13263. case GGML_UNARY_OP_CEIL:
  13264. tensor_clone = ggml_ceil(ggml_ctx, src_clone[0]);
  13265. break;
  13266. case GGML_UNARY_OP_FLOOR:
  13267. tensor_clone = ggml_floor(ggml_ctx, src_clone[0]);
  13268. break;
  13269. case GGML_UNARY_OP_TRUNC:
  13270. tensor_clone = ggml_trunc(ggml_ctx, src_clone[0]);
  13271. break;
  13272. default:
  13273. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  13274. GGML_ABORT("fatal error");
  13275. }
  13276. } else if (tensor->op == GGML_OP_GLU) {
  13277. if (src_clone[1] == nullptr) {
  13278. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  13279. } else {
  13280. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  13281. }
  13282. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  13283. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  13284. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  13285. if (tensor->src[1] == nullptr) {
  13286. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  13287. tensor_clone->type = tensor->type;
  13288. } else {
  13289. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  13290. }
  13291. } else if (tensor->op == GGML_OP_CONT) {
  13292. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  13293. } else if (tensor->op == GGML_OP_RESHAPE) {
  13294. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  13295. } else if (tensor->op == GGML_OP_VIEW) {
  13296. 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]);
  13297. } else if (tensor->op == GGML_OP_PERMUTE) {
  13298. int32_t * params = (int32_t *)tensor->op_params;
  13299. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  13300. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  13301. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  13302. } else if (tensor->op == GGML_OP_GET_ROWS) {
  13303. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  13304. } else if (tensor->op == GGML_OP_ARGSORT) {
  13305. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  13306. } else if (tensor->op == GGML_OP_TOP_K) {
  13307. tensor_clone = ggml_top_k(ggml_ctx, src_clone[0], tensor->ne[0]);
  13308. } else if (tensor->op == GGML_OP_SUM) {
  13309. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  13310. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  13311. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  13312. } else if (tensor->op == GGML_OP_CUMSUM) {
  13313. tensor_clone = ggml_cumsum(ggml_ctx, src_clone[0]);
  13314. } else if (tensor->op == GGML_OP_MEAN) {
  13315. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  13316. } else if (tensor->op == GGML_OP_ARGMAX) {
  13317. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  13318. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  13319. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  13320. } else if (tensor->op == GGML_OP_SOLVE_TRI) {
  13321. tensor_clone = ggml_solve_tri(ggml_ctx, src_clone[0], src_clone[1], true, true, false);
  13322. } else if (tensor->op == GGML_OP_IM2COL) {
  13323. const int32_t s0 = tensor->op_params[0];
  13324. const int32_t s1 = tensor->op_params[1];
  13325. const int32_t p0 = tensor->op_params[2];
  13326. const int32_t p1 = tensor->op_params[3];
  13327. const int32_t d0 = tensor->op_params[4];
  13328. const int32_t d1 = tensor->op_params[5];
  13329. const bool is_2D = tensor->op_params[6] == 1;
  13330. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  13331. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  13332. const int32_t s0 = tensor->op_params[0];
  13333. const int32_t s1 = tensor->op_params[1];
  13334. const int32_t s2 = tensor->op_params[2];
  13335. const int32_t p0 = tensor->op_params[3];
  13336. const int32_t p1 = tensor->op_params[4];
  13337. const int32_t p2 = tensor->op_params[5];
  13338. const int32_t d0 = tensor->op_params[6];
  13339. const int32_t d1 = tensor->op_params[7];
  13340. const int32_t d2 = tensor->op_params[8];
  13341. const int32_t IC = tensor->op_params[9];
  13342. 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);
  13343. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  13344. const int32_t dim = tensor->op_params[0];
  13345. const int32_t max_period = tensor->op_params[1];
  13346. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  13347. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  13348. const int32_t s0 = tensor->op_params[0];
  13349. const int32_t p0 = tensor->op_params[1];
  13350. const int32_t d0 = tensor->op_params[2];
  13351. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  13352. } else if (tensor->op == GGML_OP_POOL_2D) {
  13353. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  13354. const int32_t k0 = tensor->op_params[1];
  13355. const int32_t k1 = tensor->op_params[2];
  13356. const int32_t s0 = tensor->op_params[3];
  13357. const int32_t s1 = tensor->op_params[4];
  13358. const int32_t p0 = tensor->op_params[5];
  13359. const int32_t p1 = tensor->op_params[6];
  13360. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  13361. } else if (tensor->op == GGML_OP_CONV_2D) {
  13362. const int32_t s0 = tensor->op_params[0];
  13363. const int32_t s1 = tensor->op_params[1];
  13364. const int32_t p0 = tensor->op_params[2];
  13365. const int32_t p1 = tensor->op_params[3];
  13366. const int32_t d0 = tensor->op_params[4];
  13367. const int32_t d1 = tensor->op_params[5];
  13368. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  13369. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  13370. const int32_t s0 = tensor->op_params[0];
  13371. const int32_t s1 = tensor->op_params[1];
  13372. const int32_t p0 = tensor->op_params[2];
  13373. const int32_t p1 = tensor->op_params[3];
  13374. const int32_t d0 = tensor->op_params[4];
  13375. const int32_t d1 = tensor->op_params[5];
  13376. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  13377. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  13378. const int32_t s = tensor->op_params[0];
  13379. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  13380. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  13381. const float * op_params = (const float *)tensor->op_params;
  13382. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  13383. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  13384. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  13385. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  13386. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  13387. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  13388. src_clone[4], src_clone[5], src_clone[6]);
  13389. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  13390. src_clone[0]->flags = tensor->src[0]->flags;
  13391. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  13392. src_clone[2], src_clone[3], src_clone[4]);
  13393. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  13394. src_clone[0]->flags = tensor->src[0]->flags;
  13395. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  13396. src_clone[2]);
  13397. } else if (tensor->op == GGML_OP_ADD_ID) {
  13398. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  13399. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  13400. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  13401. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  13402. } else if (tensor->op == GGML_OP_SSM_CONV) {
  13403. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  13404. } else if (tensor->op == GGML_OP_ROLL) {
  13405. const int32_t s0 = tensor->op_params[0];
  13406. const int32_t s1 = tensor->op_params[1];
  13407. const int32_t s2 = tensor->op_params[2];
  13408. const int32_t s3 = tensor->op_params[3];
  13409. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  13410. }
  13411. else {
  13412. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  13413. GGML_ABORT("fatal error");
  13414. }
  13415. cloned_tensors[tensor] = tensor_clone;
  13416. }
  13417. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  13418. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  13419. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  13420. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13421. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  13422. }
  13423. comp_size = ggml_nbytes(tensor_clone);
  13424. comp_result = malloc(comp_size);
  13425. memcpy(comp_result, tensor_clone->data, comp_size);
  13426. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13427. for (auto m : cloned_mallocs) {
  13428. free(m);
  13429. }
  13430. ggml_free(ggml_ctx);
  13431. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  13432. }
  13433. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  13434. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  13435. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  13436. return;
  13437. }
  13438. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  13439. return;
  13440. }
  13441. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  13442. ggml_tensor * src0 = tensor->src[0];
  13443. ggml_tensor * src1 = tensor->src[1];
  13444. ggml_tensor * src2 = tensor->src[2];
  13445. ggml_tensor * src3 = tensor->src[3];
  13446. void * tensor_data = tensor->data;
  13447. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13448. size_t tensor_size = ggml_nbytes(tensor);
  13449. tensor_data = malloc(tensor_size);
  13450. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  13451. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  13452. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  13453. if (offset + tensor_size >= buffer_gpu->size) {
  13454. tensor_size = buffer_gpu->size - offset;
  13455. }
  13456. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  13457. }
  13458. float first_error_result = -1.0f;
  13459. float first_error_correct = -1.0f;
  13460. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  13461. double avg_err = 0.0;
  13462. size_t counter = 0;
  13463. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  13464. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  13465. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  13466. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  13467. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  13468. float correct = 0.0f;
  13469. float result = 0.0f;
  13470. if (buffer_size_fit) {
  13471. if (tensor->type == GGML_TYPE_F32) {
  13472. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13473. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13474. } else if (tensor->type == GGML_TYPE_F16) {
  13475. 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]));
  13476. 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]));
  13477. } else if (tensor->type == GGML_TYPE_BF16) {
  13478. 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]));
  13479. 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]));
  13480. } else if (tensor->type == GGML_TYPE_I32) {
  13481. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13482. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13483. } else if (tensor->type == GGML_TYPE_I64) {
  13484. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13485. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13486. } else {
  13487. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  13488. }
  13489. } else {
  13490. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  13491. GGML_ABORT("fatal error");
  13492. }
  13493. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  13494. 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;
  13495. 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;
  13496. if (src0 != nullptr) {
  13497. 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;
  13498. }
  13499. if (src1 != nullptr) {
  13500. 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;
  13501. }
  13502. if (src2 != nullptr) {
  13503. 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;
  13504. }
  13505. if (src3 != nullptr) {
  13506. 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;
  13507. }
  13508. 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;
  13509. std::cerr << std::endl << "Result:" << std::endl;
  13510. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  13511. std::cerr << std::endl << "Correct:" << std::endl;
  13512. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  13513. std::cerr << std::endl;
  13514. std::vector<const ggml_tensor *> done;
  13515. ggml_vk_print_graph_origin(tensor, done);
  13516. GGML_ABORT("fatal error");
  13517. }
  13518. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  13519. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  13520. first_error[0] = i0;
  13521. first_error[1] = i1;
  13522. first_error[2] = i2;
  13523. first_error[3] = i3;
  13524. first_error_result = result;
  13525. first_error_correct = correct;
  13526. }
  13527. // Special case, value is infinite, avoid NaN result in avg_err
  13528. // NaN also appears in results, if both are nan error is 0
  13529. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  13530. avg_err += std::fabs(correct - result) / denom;
  13531. }
  13532. counter++;
  13533. }
  13534. }
  13535. }
  13536. }
  13537. avg_err /= counter;
  13538. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13539. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13540. 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;
  13541. if (src0 != nullptr) {
  13542. 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;
  13543. }
  13544. if (src1 != nullptr) {
  13545. 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;
  13546. }
  13547. if (src2 != nullptr) {
  13548. 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;
  13549. }
  13550. if (src3 != nullptr) {
  13551. 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;
  13552. }
  13553. 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;
  13554. std::cerr << std::endl << "Result:" << std::endl;
  13555. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13556. std::cerr << std::endl << "Correct:" << std::endl;
  13557. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  13558. std::cerr << std::endl;
  13559. std::vector<const ggml_tensor *> done;
  13560. ggml_vk_print_graph_origin(tensor, done);
  13561. }
  13562. if (avg_err > 0.5 || std::isnan(avg_err)) {
  13563. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13564. 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;
  13565. if (src0 != nullptr) {
  13566. 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;
  13567. }
  13568. if (src1 != nullptr) {
  13569. 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;
  13570. }
  13571. if (src2 != nullptr) {
  13572. 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;
  13573. }
  13574. if (src3 != nullptr) {
  13575. 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;
  13576. }
  13577. 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;
  13578. std::cerr << std::endl << "Result:" << std::endl;
  13579. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  13580. std::cerr << std::endl << "Correct:" << std::endl;
  13581. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  13582. std::cerr << std::endl;
  13583. std::vector<const ggml_tensor *> done;
  13584. ggml_vk_print_graph_origin(tensor, done);
  13585. GGML_ABORT("fatal error");
  13586. } else {
  13587. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  13588. }
  13589. free(comp_result);
  13590. comp_result = nullptr;
  13591. comp_size = 0;
  13592. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13593. free(tensor_data);
  13594. }
  13595. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  13596. }
  13597. #endif
  13598. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)