ggml-vulkan.cpp 778 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438
  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_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  363. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  364. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  365. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  366. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  367. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  368. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  369. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  370. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  371. //node #982 ( GET_ROWS): ffn_moe_weights-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 (re ( 0K) [Vulka ] ffn_moe_topk-15 ( 0K) [Vulka ]
  372. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  373. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  374. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  375. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  376. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  377. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  378. { 1, 0, 0 }, // reshape->src[0] == softmax
  379. { 2, 0, 0 }, // argsort->src[0] == softmax
  380. { 3, 0, 2 }, // view->src[0] == argsort
  381. { 4, 0, 1 }, // get_rows->src[0] == reshape
  382. { 4, 1, 3 }, // get_rows->src[1] == view
  383. { 5, 0, 4 }, // reshape->src[0] == get_rows
  384. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  385. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  386. { 8, 0, 5 }, // div->src[0] == reshape
  387. { 8, 1, 7 }, // div->src[1] == clamp
  388. { 9, 0, 8 }, // reshape->src[0] == div
  389. };
  390. // same as early_softmax_norm but ending after the get_rows
  391. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  392. { 1, 0, 0 }, // reshape->src[0] == softmax
  393. { 2, 0, 0 }, // argsort->src[0] == softmax
  394. { 3, 0, 2 }, // view->src[0] == argsort
  395. { 4, 0, 1 }, // get_rows->src[0] == reshape
  396. { 4, 1, 3 }, // get_rows->src[1] == view
  397. };
  398. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  399. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  400. //node #654 ( GET_ROWS): ffn_moe_weights-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 (re ( 0K) [Vulka ] ffn_moe_topk-11 ( 0K) [Vulka ]
  401. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  402. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  403. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  404. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  405. { 1, 0, 0 }, // view->src[0] == argsort
  406. { 2, 1, 1 }, // get_rows->src[1] == view
  407. { 3, 0, 2 }, // reshape->src[0] == get_rows
  408. { 4, 0, 3 }, // soft_max->src[0] == reshape
  409. { 5, 0, 4 }, // reshape->src[0] == soft_max
  410. };
  411. enum topk_moe_mode {
  412. TOPK_MOE_EARLY_SOFTMAX,
  413. TOPK_MOE_EARLY_SOFTMAX_NORM,
  414. TOPK_MOE_LATE_SOFTMAX,
  415. TOPK_MOE_COUNT,
  416. };
  417. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  418. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  419. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  420. TOPK_MOE_LATE_SOFTMAX;
  421. return mode;
  422. }
  423. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  424. { 1, 0, 0 }, // view->src[0] == rope
  425. { 2, 0, 1 }, // set_rows->src[0] == view
  426. };
  427. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  428. { 1, 0, 0 }, // mul->src[0] == rms
  429. { 2, 0, 1 }, // rope->src[0] == mul
  430. { 3, 0, 2 }, // view->src[0] == rope
  431. { 4, 0, 3 }, // set_rows->src[0] == view
  432. };
  433. struct vk_device_struct {
  434. std::recursive_mutex mutex;
  435. vk::PhysicalDevice physical_device;
  436. vk::PhysicalDeviceProperties properties;
  437. std::string name;
  438. uint64_t max_memory_allocation_size;
  439. uint64_t max_buffer_size;
  440. uint64_t suballocation_block_size;
  441. bool fp16;
  442. bool bf16;
  443. bool pipeline_robustness;
  444. bool memory_priority;
  445. vk::Device device;
  446. uint32_t vendor_id;
  447. vk::DriverId driver_id;
  448. vk_device_architecture architecture;
  449. vk_queue compute_queue;
  450. vk_queue transfer_queue;
  451. bool single_queue;
  452. bool support_async;
  453. uint32_t subgroup_size;
  454. uint32_t subgroup_size_log2;
  455. uint32_t shader_core_count;
  456. bool uma;
  457. bool prefer_host_memory;
  458. bool float_controls_rte_fp16;
  459. bool subgroup_arithmetic;
  460. bool subgroup_shuffle;
  461. bool subgroup_ballot;
  462. bool subgroup_clustered;
  463. bool subgroup_vote;
  464. bool multi_add;
  465. bool shader_int64;
  466. bool buffer_device_address;
  467. bool vulkan_memory_model;
  468. bool add_rms_fusion;
  469. uint32_t partials_binding_alignment;
  470. bool integer_dot_product;
  471. // 0: default, 1: force mmvq, -1: disable mmvq
  472. int32_t mmvq_mode;
  473. bool subgroup_size_control;
  474. uint32_t subgroup_min_size;
  475. uint32_t subgroup_max_size;
  476. bool subgroup_require_full_support;
  477. // floor(log2(maxComputeWorkGroupInvocations))
  478. uint32_t max_workgroup_size_log2 {};
  479. bool coopmat_support;
  480. bool coopmat_acc_f32_support {};
  481. bool coopmat_acc_f16_support {};
  482. bool coopmat_bf16_support {};
  483. bool coopmat_support_16x16x16_f16acc {};
  484. bool coopmat_support_16x16x16_f32acc {};
  485. bool coopmat1_fa_support {};
  486. uint32_t coopmat_m;
  487. uint32_t coopmat_n;
  488. uint32_t coopmat_k;
  489. bool coopmat_int_support;
  490. uint32_t coopmat_int_m;
  491. uint32_t coopmat_int_n;
  492. uint32_t coopmat_int_k;
  493. bool coopmat2;
  494. bool pipeline_executable_properties_support {};
  495. size_t idx;
  496. bool mul_mat_l[GGML_TYPE_COUNT];
  497. bool mul_mat_m[GGML_TYPE_COUNT];
  498. bool mul_mat_s[GGML_TYPE_COUNT];
  499. bool mul_mat_id_l[GGML_TYPE_COUNT];
  500. bool mul_mat_id_m[GGML_TYPE_COUNT];
  501. bool mul_mat_id_s[GGML_TYPE_COUNT];
  502. vk::DescriptorSetLayout dsl;
  503. vk_matmul_pipeline pipeline_matmul_f32 {};
  504. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  505. vk_matmul_pipeline pipeline_matmul_bf16 {};
  506. vk_matmul_pipeline2 pipeline_matmul_f16;
  507. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  508. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  509. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  510. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  511. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  512. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  513. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  514. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  515. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  516. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  517. vk_pipeline pipeline_matmul_split_k_reduce;
  518. vk_pipeline pipeline_quantize_q8_1_x4;
  519. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  520. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  521. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  522. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  523. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  524. vk_pipeline pipeline_dequant_mul_mat_vec_id_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  525. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  526. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  527. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  528. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  529. vk_pipeline pipeline_acc_f32;
  530. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  531. vk_pipeline pipeline_add[2][2][2];
  532. vk_pipeline pipeline_add_norepeat[2][2][2];
  533. vk_pipeline pipeline_sub[2][2][2];
  534. vk_pipeline pipeline_sub_norepeat[2][2][2];
  535. vk_pipeline pipeline_mul[2][2][2];
  536. vk_pipeline pipeline_mul_norepeat[2][2][2];
  537. vk_pipeline pipeline_div[2][2][2];
  538. vk_pipeline pipeline_div_norepeat[2][2][2];
  539. vk_pipeline pipeline_add_rms[2][2][2];
  540. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  541. // indexed by num_additional_fused_ops == num_adds - 1
  542. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  543. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  544. vk_pipeline pipeline_add_id_f32;
  545. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  546. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32, pipeline_upscale_bilinear_antialias_f32;
  547. vk_pipeline pipeline_scale_f32;
  548. vk_pipeline pipeline_sqr_f32;
  549. vk_pipeline pipeline_sqrt_f32;
  550. vk_pipeline pipeline_sin_f32;
  551. vk_pipeline pipeline_cos_f32;
  552. vk_pipeline pipeline_log[2];
  553. vk_pipeline pipeline_tri[2];
  554. vk_pipeline pipeline_diag[2];
  555. vk_pipeline pipeline_clamp_f32;
  556. vk_pipeline pipeline_pad_f32;
  557. vk_pipeline pipeline_roll_f32;
  558. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  559. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
  560. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
  561. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  562. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  563. vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
  564. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  565. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  566. vk_pipeline pipeline_norm_f32;
  567. vk_pipeline pipeline_group_norm_f32;
  568. vk_pipeline pipeline_rms_norm_f32;
  569. vk_pipeline pipeline_rms_norm_mul_f32;
  570. vk_pipeline pipeline_rms_norm_partials_f32;
  571. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  572. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  573. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  574. vk_pipeline pipeline_rms_norm_back_f32;
  575. vk_pipeline pipeline_l2_norm_f32;
  576. // [src/dst 0=fp32,1=fp16]
  577. vk_pipeline pipeline_exp[2];
  578. vk_pipeline pipeline_gelu[2];
  579. vk_pipeline pipeline_gelu_erf[2];
  580. vk_pipeline pipeline_gelu_quick[2];
  581. vk_pipeline pipeline_silu[2];
  582. vk_pipeline pipeline_relu[2];
  583. vk_pipeline pipeline_xielu[2];
  584. vk_pipeline pipeline_neg[2];
  585. vk_pipeline pipeline_tanh[2];
  586. vk_pipeline pipeline_sigmoid[2];
  587. vk_pipeline pipeline_hardsigmoid[2];
  588. vk_pipeline pipeline_hardswish[2];
  589. vk_pipeline pipeline_abs[2];
  590. vk_pipeline pipeline_softplus[2];
  591. vk_pipeline pipeline_step[2];
  592. vk_pipeline pipeline_round[2];
  593. vk_pipeline pipeline_ceil[2];
  594. vk_pipeline pipeline_floor[2];
  595. vk_pipeline pipeline_trunc[2];
  596. vk_pipeline pipeline_add1_f16_f16;
  597. vk_pipeline pipeline_add1_f16_f32;
  598. vk_pipeline pipeline_add1_f32_f32;
  599. vk_pipeline pipeline_arange_f32;
  600. vk_pipeline pipeline_fill_f32;
  601. vk_pipeline pipeline_geglu[2];
  602. vk_pipeline pipeline_reglu[2];
  603. vk_pipeline pipeline_swiglu[2];
  604. vk_pipeline pipeline_swiglu_oai[2];
  605. vk_pipeline pipeline_geglu_erf[2];
  606. vk_pipeline pipeline_geglu_quick[2];
  607. vk_pipeline pipeline_leaky_relu_f32;
  608. vk_pipeline pipeline_silu_back_f32;
  609. vk_pipeline pipeline_diag_mask_inf_f32;
  610. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  611. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  612. vk_pipeline pipeline_soft_max_back_f32;
  613. vk_pipeline pipeline_soft_max_large1_f32, pipeline_soft_max_large1_f32_f16;
  614. vk_pipeline pipeline_soft_max_large2_f32, pipeline_soft_max_large2_f32_f16;
  615. vk_pipeline pipeline_soft_max_large3_f32, pipeline_soft_max_large3_f32_f16;
  616. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  617. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  618. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16, pipeline_rope_multi_f32_f16;
  619. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  620. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  621. vk_pipeline pipeline_argsort_large_f32[num_argsort_pipelines];
  622. vk_pipeline pipeline_topk_f32[num_topk_pipelines];
  623. vk_pipeline pipeline_sum_rows_f32;
  624. vk_pipeline pipeline_cumsum_f32;
  625. vk_pipeline pipeline_argmax_f32;
  626. vk_pipeline pipeline_count_equal_i32;
  627. std::map<vk_solve_tri_pipeline_state, vk_pipeline> pipeline_solve_tri_f32;
  628. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  629. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  630. vk_pipeline pipeline_timestep_embedding_f32;
  631. vk_pipeline pipeline_conv_transpose_1d_f32;
  632. vk_pipeline pipeline_pool2d_f32;
  633. vk_pipeline pipeline_rwkv_wkv6_f32;
  634. vk_pipeline pipeline_rwkv_wkv7_f32;
  635. vk_pipeline pipeline_ssm_scan_f32_d128;
  636. vk_pipeline pipeline_ssm_scan_f32_d256;
  637. vk_pipeline pipeline_ssm_conv_f32;
  638. vk_pipeline pipeline_opt_step_adamw_f32;
  639. vk_pipeline pipeline_opt_step_sgd_f32;
  640. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  641. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  642. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  643. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  644. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  645. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  646. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  647. vk_pipeline pipeline_flash_attn_split_k_reduce;
  648. // [2] is for whether to take n_experts from spec constant (0) or push constant (1)
  649. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT][2];
  650. std::vector<vk_pipeline_ref> all_pipelines;
  651. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  652. vk::Fence fence;
  653. vk_buffer sync_staging;
  654. ggml_backend_buffer_type buffer_type;
  655. bool disable_fusion;
  656. bool disable_host_visible_vidmem;
  657. bool allow_sysmem_fallback;
  658. bool disable_graph_optimize;
  659. #ifdef GGML_VULKAN_MEMORY_DEBUG
  660. std::unique_ptr<vk_memory_logger> memory_logger;
  661. #endif
  662. ~vk_device_struct() {
  663. VK_LOG_DEBUG("destroy device " << name);
  664. device.destroyFence(fence);
  665. ggml_vk_destroy_buffer(sync_staging);
  666. compute_queue.cmd_pool.destroy(device);
  667. transfer_queue.cmd_pool.destroy(device);
  668. for (auto& pipeline : all_pipelines) {
  669. if (pipeline.expired()) {
  670. continue;
  671. }
  672. vk_pipeline pl = pipeline.lock();
  673. ggml_vk_destroy_pipeline(device, pl);
  674. }
  675. all_pipelines.clear();
  676. device.destroyDescriptorSetLayout(dsl);
  677. device.destroy();
  678. }
  679. };
  680. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  681. cmd_buffer_idx = 0;
  682. q = q_;
  683. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  684. pool = device->device.createCommandPool(command_pool_create_info);
  685. }
  686. void vk_command_pool::destroy(vk::Device& device) {
  687. device.destroyCommandPool(pool);
  688. pool = nullptr;
  689. cmd_buffers.clear();
  690. }
  691. struct vk_buffer_struct {
  692. vk::Buffer buffer = VK_NULL_HANDLE;
  693. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  694. vk::MemoryPropertyFlags memory_property_flags;
  695. void * ptr;
  696. size_t size = 0;
  697. vk::DeviceAddress bda_addr {};
  698. vk_device device;
  699. ~vk_buffer_struct() {
  700. if (size == 0) {
  701. return;
  702. }
  703. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  704. device->device.freeMemory(device_memory);
  705. device->device.destroyBuffer(buffer);
  706. }
  707. };
  708. struct vk_subbuffer {
  709. vk_buffer buffer;
  710. uint64_t offset;
  711. uint64_t size;
  712. operator vk::DescriptorBufferInfo() const {
  713. return { buffer->buffer, offset, size };
  714. }
  715. };
  716. // vk_event is used for the event-related backend interfaces. It uses 'event' for
  717. // event_wait and 'fence' for event_synchronize. Polling on an event for
  718. // event_synchronize wouldn't be sufficient to wait for command buffers to complete,
  719. // and would lead to validation errors.
  720. struct vk_event {
  721. vk::Event event;
  722. vk::Fence fence;
  723. };
  724. struct vk_semaphore {
  725. vk::Semaphore s;
  726. uint64_t value;
  727. };
  728. struct vk_submission {
  729. vk::CommandBuffer buffer;
  730. std::vector<vk_semaphore> wait_semaphores;
  731. std::vector<vk_semaphore> signal_semaphores;
  732. };
  733. typedef std::vector<vk_submission> vk_sequence;
  734. struct vk_mat_mat_push_constants {
  735. uint32_t M; uint32_t N; uint32_t K;
  736. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  737. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  738. uint32_t k_split;
  739. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  740. uint32_t padded_N;
  741. };
  742. #define MAT_VEC_FUSION_FLAGS_BIAS0 0x1
  743. #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
  744. #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
  745. #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
  746. struct vk_mat_vec_push_constants {
  747. uint32_t ncols;
  748. uint32_t stride_a;
  749. uint32_t stride_b;
  750. uint32_t stride_d;
  751. uint32_t batch_stride_a;
  752. uint32_t batch_stride_b;
  753. uint32_t batch_stride_d;
  754. uint32_t fusion_flags;
  755. uint32_t ne02;
  756. uint32_t ne12;
  757. uint32_t broadcast2;
  758. uint32_t broadcast3;
  759. };
  760. struct vk_mat_vec_p021_push_constants {
  761. uint32_t ncols_x;
  762. uint32_t nrows_x;
  763. uint32_t nchannels_x;
  764. uint32_t nchannels_y;
  765. uint32_t b_offset;
  766. uint32_t d_offset;
  767. uint32_t fusion_flags;
  768. };
  769. struct vk_mat_vec_nc_push_constants {
  770. uint32_t ncols_x;
  771. uint32_t nrows_x;
  772. uint32_t row_stride_x;
  773. uint32_t channel_stride_x;
  774. uint32_t channel_stride_y;
  775. uint32_t channel_x_divisor;
  776. uint32_t ne12;
  777. uint32_t b_offset;
  778. uint32_t d_offset;
  779. uint32_t nb03;
  780. uint32_t nb13;
  781. uint32_t nb23;
  782. uint32_t fusion_flags;
  783. };
  784. struct vk_mat_mat_id_push_constants {
  785. uint32_t M; uint32_t N; uint32_t K;
  786. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  787. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  788. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  789. uint32_t padded_N;
  790. };
  791. struct vk_mat_vec_id_push_constants {
  792. uint32_t ncols;
  793. uint32_t stride_a;
  794. uint32_t stride_b;
  795. uint32_t stride_d;
  796. uint32_t batch_stride_a;
  797. uint32_t batch_stride_b;
  798. uint32_t batch_stride_d;
  799. uint32_t fusion_flags;
  800. uint32_t nei0;
  801. uint32_t ne11;
  802. };
  803. struct vk_flash_attn_push_constants {
  804. uint32_t N;
  805. uint32_t KV;
  806. uint32_t ne1;
  807. uint32_t ne2;
  808. uint32_t ne3;
  809. uint32_t neq2;
  810. uint32_t neq3;
  811. uint32_t nek2;
  812. uint32_t nek3;
  813. uint32_t nev2;
  814. uint32_t nev3;
  815. uint32_t nem1;
  816. uint32_t nem2;
  817. uint32_t nem3;
  818. uint32_t nb01;
  819. uint32_t nb02;
  820. uint32_t nb03;
  821. uint32_t nb11;
  822. uint32_t nb12;
  823. uint32_t nb13;
  824. uint32_t nb21;
  825. uint32_t nb22;
  826. uint32_t nb23;
  827. float scale;
  828. float max_bias;
  829. float logit_softcap;
  830. uint32_t mask_n_head_log2;
  831. float m0;
  832. float m1;
  833. uint32_t gqa_ratio;
  834. uint32_t split_kv;
  835. uint32_t k_num;
  836. };
  837. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  838. struct vk_op_push_constants {
  839. uint32_t KX;
  840. uint32_t KY;
  841. float param1;
  842. float param2;
  843. float param3;
  844. float param4;
  845. };
  846. struct vk_op_glu_push_constants {
  847. uint32_t N;
  848. uint32_t ne00;
  849. uint32_t ne20;
  850. uint32_t mode; // 0: default, 1: swapped, 2: split
  851. float alpha; // for swiglu_oai
  852. float limit;
  853. };
  854. struct vk_op_unary_push_constants {
  855. uint32_t ne;
  856. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  857. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  858. uint32_t misalign_offsets;
  859. float param1; float param2;
  860. uint32_t ne0_012mp; uint32_t ne0_012L;
  861. uint32_t ne0_01mp; uint32_t ne0_01L;
  862. uint32_t ne0_0mp; uint32_t ne0_0L;
  863. uint32_t ne1_012mp; uint32_t ne1_012L;
  864. uint32_t ne1_01mp; uint32_t ne1_01L;
  865. uint32_t ne1_0mp; uint32_t ne1_0L;
  866. };
  867. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  868. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  869. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  870. ne = ne != 0 ? ne : ggml_nelements(dst);
  871. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  872. vk_op_unary_push_constants p{};
  873. p.ne = (uint32_t)ne;
  874. size_t src0_tsize = ggml_type_size(src0->type);
  875. p.ne00 = (uint32_t)src0->ne[0];
  876. p.ne01 = (uint32_t)src0->ne[1];
  877. p.ne02 = (uint32_t)src0->ne[2];
  878. p.ne03 = (uint32_t)src0->ne[3];
  879. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  880. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  881. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  882. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  883. size_t dst_tsize = ggml_type_size(dst->type);
  884. p.ne10 = (uint32_t)dst->ne[0];
  885. p.ne11 = (uint32_t)dst->ne[1];
  886. p.ne12 = (uint32_t)dst->ne[2];
  887. p.ne13 = (uint32_t)dst->ne[3];
  888. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  889. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  890. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  891. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  892. return p; // offsets are initialized later in ggml_vk_op
  893. }
  894. struct vk_op_pad_push_constants {
  895. uint32_t ne;
  896. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  897. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  898. uint32_t misalign_offsets;
  899. uint32_t circular;
  900. uint32_t lp0; uint32_t rp0;
  901. uint32_t lp1; uint32_t rp1;
  902. uint32_t lp2; uint32_t rp2;
  903. uint32_t lp3; uint32_t rp3;
  904. };
  905. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  906. int64_t ne = ggml_nelements(dst);
  907. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  908. vk_op_pad_push_constants p{};
  909. p.ne = (uint32_t)ne;
  910. size_t src0_tsize = ggml_type_size(src0->type);
  911. p.ne00 = (uint32_t)src0->ne[0];
  912. p.ne01 = (uint32_t)src0->ne[1];
  913. p.ne02 = (uint32_t)src0->ne[2];
  914. p.ne03 = (uint32_t)src0->ne[3];
  915. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  916. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  917. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  918. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  919. size_t dst_tsize = ggml_type_size(dst->type);
  920. p.ne10 = (uint32_t)dst->ne[0];
  921. p.ne11 = (uint32_t)dst->ne[1];
  922. p.ne12 = (uint32_t)dst->ne[2];
  923. p.ne13 = (uint32_t)dst->ne[3];
  924. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  925. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  926. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  927. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  928. p.lp0 = dst->op_params[0];
  929. p.rp0 = dst->op_params[1];
  930. p.lp1 = dst->op_params[2];
  931. p.rp1 = dst->op_params[3];
  932. p.lp2 = dst->op_params[4];
  933. p.rp2 = dst->op_params[5];
  934. p.lp3 = dst->op_params[6];
  935. p.rp3 = dst->op_params[7];
  936. p.circular = dst->op_params[8];
  937. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  938. }
  939. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  940. // Precompute mp (m' in the paper) and L such that division
  941. // can be computed using a multiply (high 32b of 64b result)
  942. // and a shift:
  943. //
  944. // n/d = (mulhi(n, mp) + n) >> L;
  945. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  946. {
  947. // compute L = ceil(log2(d));
  948. L = 0;
  949. while (L < 32 && (uint32_t{1} << L) < d) {
  950. L++;
  951. }
  952. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  953. }
  954. template <typename T> void init_pushconst_fastdiv(T &p) {
  955. GGML_UNUSED(p);
  956. static_assert(!std::is_const<T>::value, "unexpected type");
  957. }
  958. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  959. // Compute magic values to divide by these six numbers.
  960. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  961. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  962. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  963. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  964. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  965. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  966. }
  967. struct vk_op_binary_push_constants {
  968. uint32_t ne;
  969. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  970. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  971. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  972. uint32_t misalign_offsets;
  973. float param1; float param2; int32_t param3;
  974. };
  975. struct vk_op_multi_add_push_constants {
  976. // shape for dst
  977. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  978. // strides for srcs+dst
  979. uint32_t nb[MAX_PARAMETER_COUNT][4];
  980. uint32_t rms_partials;
  981. };
  982. // update multi_add.comp if this changes
  983. static_assert(MAX_PARAMETER_COUNT == 12);
  984. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  985. struct vk_op_topk_moe_push_constants {
  986. uint32_t n_rows;
  987. uint32_t n_experts_push;
  988. uint32_t n_expert_used;
  989. float clamp_min;
  990. float clamp_max;
  991. };
  992. struct vk_op_add_id_push_constants {
  993. uint32_t ne0;
  994. uint32_t ne1;
  995. uint32_t s01;
  996. uint32_t s02;
  997. uint32_t s11;
  998. uint32_t s21;
  999. };
  1000. struct vk_op_diag_mask_push_constants {
  1001. uint32_t ncols;
  1002. uint32_t rows_per_channel;
  1003. int32_t n_past;
  1004. };
  1005. struct vk_op_rope_push_constants {
  1006. uint32_t rope_mode;
  1007. uint32_t ncols;
  1008. uint32_t nrows;
  1009. uint32_t n_dims;
  1010. float freq_scale;
  1011. uint32_t p_delta_rows;
  1012. float freq_base;
  1013. float ext_factor;
  1014. float attn_factor;
  1015. float corr_dims[2];
  1016. float theta_scale;
  1017. uint32_t has_ff;
  1018. uint32_t ne02;
  1019. uint32_t s1;
  1020. uint32_t s2;
  1021. int32_t sections[4];
  1022. uint32_t is_imrope;
  1023. uint32_t is_back;
  1024. uint32_t set_rows_stride;
  1025. };
  1026. // For fused rms_norm+mul+rope(+view+set_rows)
  1027. struct vk_op_rms_norm_mul_rope_push_constants {
  1028. vk_op_binary_push_constants bin;
  1029. vk_op_rope_push_constants rope;
  1030. };
  1031. struct vk_op_soft_max_push_constants {
  1032. uint32_t KX;
  1033. uint32_t KY;
  1034. uint32_t ne00;
  1035. uint32_t ne01;
  1036. uint32_t ne02;
  1037. uint32_t ne12;
  1038. uint32_t ne13;
  1039. uint32_t nb11;
  1040. uint32_t nb12;
  1041. uint32_t nb13;
  1042. float scale;
  1043. float max_bias;
  1044. float m0;
  1045. float m1;
  1046. uint32_t n_head_log2;
  1047. uint32_t nrows_x;
  1048. uint32_t has_sinks;
  1049. };
  1050. struct vk_op_argsort_push_constants {
  1051. uint32_t ncols;
  1052. uint32_t ncols_padded;
  1053. uint32_t ncols_padded_log2;
  1054. uint32_t nrows;
  1055. uint32_t order;
  1056. uint32_t outer_start;
  1057. uint32_t outer_end;
  1058. uint32_t inner_start;
  1059. uint32_t inner_end;
  1060. };
  1061. struct vk_op_topk_push_constants {
  1062. uint32_t orig_ncols;
  1063. uint32_t ncols_input;
  1064. uint32_t ncols_output;
  1065. uint32_t k;
  1066. uint32_t nrows;
  1067. uint32_t first_pass;
  1068. uint32_t last_pass;
  1069. };
  1070. struct vk_op_im2col_push_constants {
  1071. uint64_t dst_addr;
  1072. uint32_t batch_offset; uint32_t offset_delta;
  1073. uint32_t IC;
  1074. uint32_t IW; uint32_t IH;
  1075. uint32_t OW; uint32_t OH;
  1076. uint32_t KW; uint32_t KH;
  1077. uint32_t pelements;
  1078. uint32_t CHW;
  1079. int32_t s0; int32_t s1;
  1080. int32_t p0; int32_t p1;
  1081. int32_t d0; int32_t d1;
  1082. uint32_t batch_IC;
  1083. };
  1084. struct vk_op_im2col_3d_push_constants {
  1085. uint64_t dst_addr;
  1086. uint32_t nb10;
  1087. uint32_t nb11;
  1088. uint32_t nb12;
  1089. uint32_t nb13;
  1090. uint32_t s0;
  1091. uint32_t s1;
  1092. uint32_t s2;
  1093. uint32_t p0;
  1094. uint32_t p1;
  1095. uint32_t p2;
  1096. uint32_t d0;
  1097. uint32_t d1;
  1098. uint32_t d2;
  1099. uint32_t IW;
  1100. uint32_t IH;
  1101. uint32_t ID;
  1102. uint32_t IC;
  1103. uint32_t KW;
  1104. uint32_t OH;
  1105. uint32_t KD_KH_KW;
  1106. uint32_t KH_KW;
  1107. uint32_t IC_KD_KH_KW;
  1108. uint32_t N_OD_OH;
  1109. uint32_t OD_OH;
  1110. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1111. uint32_t OH_OW_IC_KD_KH_KW;
  1112. uint32_t OW_IC_KD_KH_KW;
  1113. uint32_t misalign_offsets;
  1114. };
  1115. struct vk_op_timestep_embedding_push_constants {
  1116. uint32_t nb1;
  1117. uint32_t dim;
  1118. uint32_t max_period;
  1119. };
  1120. struct vk_op_conv_transpose_1d_push_constants {
  1121. uint32_t Cout;
  1122. uint32_t Cin;
  1123. uint32_t K;
  1124. uint32_t L;
  1125. uint32_t KL;
  1126. uint32_t nb01;
  1127. uint32_t nb02;
  1128. uint32_t nb11;
  1129. uint32_t nb1;
  1130. int32_t s0;
  1131. };
  1132. struct vk_op_pool2d_push_constants {
  1133. uint32_t IW; uint32_t IH;
  1134. uint32_t OW; uint32_t OH;
  1135. uint32_t OC;
  1136. uint32_t pelements;
  1137. uint32_t op;
  1138. int32_t k0; int32_t k1;
  1139. int32_t s0; int32_t s1;
  1140. int32_t p0; int32_t p1;
  1141. };
  1142. struct vk_op_rwkv_wkv6_push_constants {
  1143. uint32_t B;
  1144. uint32_t T;
  1145. uint32_t C;
  1146. uint32_t H;
  1147. };
  1148. struct vk_op_rwkv_wkv7_push_constants {
  1149. uint32_t B;
  1150. uint32_t T;
  1151. uint32_t C;
  1152. uint32_t H;
  1153. };
  1154. struct vk_op_ssm_scan_push_constants {
  1155. uint32_t nb02, nb03, nb12, nb13;
  1156. uint32_t nb21, nb22, nb31;
  1157. uint32_t nb42, nb43, nb52, nb53;
  1158. uint32_t s_off;
  1159. uint32_t n_head, d_head, n_group, n_tok;
  1160. };
  1161. struct vk_op_ssm_conv_push_constants {
  1162. uint32_t nb01, nb02;
  1163. uint32_t nb11;
  1164. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1165. uint32_t nc, ncs, nr, n_t, n_s;
  1166. };
  1167. struct vk_op_conv2d_push_constants {
  1168. uint32_t Cout;
  1169. uint32_t Cin;
  1170. uint32_t N;
  1171. uint32_t W;
  1172. uint32_t H;
  1173. uint32_t OW;
  1174. uint32_t OH;
  1175. uint32_t nb01;
  1176. uint32_t nb02;
  1177. uint32_t nb03;
  1178. uint32_t nb11;
  1179. uint32_t nb12;
  1180. uint32_t nb13;
  1181. uint32_t nb1;
  1182. uint32_t nb2;
  1183. uint32_t nb3;
  1184. // init_fastdiv_values constants for dividing by OW, OW*OH
  1185. uint32_t OWmp; uint32_t OWL;
  1186. uint32_t OWOHmp; uint32_t OWOHL;
  1187. };
  1188. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1189. // Compute magic values to divide by OW, OW*OH
  1190. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1191. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1192. }
  1193. struct vk_op_conv2d_dw_push_constants {
  1194. uint32_t ne;
  1195. uint32_t batches;
  1196. uint32_t channels;
  1197. uint32_t dst_w;
  1198. uint32_t dst_h;
  1199. uint32_t src_w;
  1200. uint32_t src_h;
  1201. uint32_t knl_w;
  1202. uint32_t knl_h;
  1203. int32_t stride_x;
  1204. int32_t stride_y;
  1205. int32_t pad_x;
  1206. int32_t pad_y;
  1207. int32_t dilation_x;
  1208. int32_t dilation_y;
  1209. };
  1210. struct vk_op_upscale_push_constants {
  1211. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1212. uint32_t ne00; uint32_t ne01;
  1213. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1214. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1215. float sf0; float sf1; float sf2; float sf3;
  1216. float pixel_offset;
  1217. };
  1218. struct vk_op_sum_rows_push_constants
  1219. {
  1220. uint32_t n_cols;
  1221. uint32_t ne01, ne02;
  1222. uint32_t nb01, nb02, nb03;
  1223. uint32_t nb11, nb12, nb13;
  1224. float weight;
  1225. uint32_t misalign_offsets;
  1226. uint32_t ne0_12mp, ne0_12L;
  1227. uint32_t ne0_1mp, ne0_1L;
  1228. };
  1229. 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) {
  1230. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1231. vk_op_sum_rows_push_constants p = {};
  1232. p.n_cols = (uint32_t)n_cols;
  1233. p.ne01 = (uint32_t)src->ne[1];
  1234. p.ne02 = (uint32_t)src->ne[2];
  1235. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1236. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1237. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1238. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1239. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1240. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1241. p.weight = 1.0f;
  1242. return p;
  1243. }
  1244. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1245. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1246. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1247. }
  1248. // Allow pre-recording command buffers
  1249. struct vk_staging_memcpy {
  1250. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1251. void * dst;
  1252. const void * src;
  1253. size_t n;
  1254. };
  1255. struct vk_staging_memset {
  1256. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1257. void * dst;
  1258. uint32_t val;
  1259. size_t n;
  1260. };
  1261. struct vk_context_struct {
  1262. vk_submission * s;
  1263. std::vector<vk_sequence> seqs;
  1264. int exit_tensor_idx;
  1265. std::vector<vk_staging_memcpy> in_memcpys;
  1266. std::vector<vk_staging_memcpy> out_memcpys;
  1267. std::vector<vk_staging_memset> memsets;
  1268. vk_command_pool * p {};
  1269. };
  1270. typedef std::shared_ptr<vk_context_struct> vk_context;
  1271. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1272. struct ggml_vk_garbage_collector {
  1273. std::vector<vk_semaphore> tl_semaphores;
  1274. std::vector<vk_semaphore> semaphores;
  1275. std::vector<vk::Event> events;
  1276. std::vector<vk_context> contexts;
  1277. };
  1278. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1279. static void ggml_vk_load_shaders(vk_device& device);
  1280. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1281. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1282. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1283. static std::string format_size(size_t size) {
  1284. const size_t kib = 1024;
  1285. const size_t mib = kib * 1024;
  1286. const size_t gib = mib * 1024;
  1287. std::ostringstream oss;
  1288. oss << std::fixed << std::setprecision(2);
  1289. if (size >= gib) {
  1290. oss << static_cast<double>(size) / gib << " GiB";
  1291. } else if (size >= mib) {
  1292. oss << static_cast<double>(size) / mib << " MiB";
  1293. } else if (size >= kib) {
  1294. oss << static_cast<double>(size) / kib << " KiB";
  1295. } else {
  1296. oss << size << " B";
  1297. }
  1298. return oss.str();
  1299. }
  1300. class vk_memory_logger {
  1301. public:
  1302. vk_memory_logger(): total_device(0), total_host(0) {}
  1303. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1304. void log_deallocation(vk_buffer_ref buf_ref);
  1305. private:
  1306. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1307. size_t total_device;
  1308. size_t total_host;
  1309. };
  1310. #else
  1311. #define VK_LOG_MEMORY(msg) ((void) 0)
  1312. #endif // GGML_VULKAN_MEMORY_DEBUG
  1313. static bool vk_perf_logger_enabled = false;
  1314. static bool vk_perf_logger_concurrent = false;
  1315. static bool vk_enable_sync_logger = false;
  1316. // number of calls between perf logger prints
  1317. static uint32_t vk_perf_logger_frequency = 1;
  1318. class vk_perf_logger {
  1319. public:
  1320. void print_timings(bool force = false) {
  1321. if (timings.empty()) {
  1322. return;
  1323. }
  1324. print_count++;
  1325. if ((print_count % vk_perf_logger_frequency) != 0 && !force) {
  1326. return;
  1327. }
  1328. print_count = 0;
  1329. uint64_t total_all_op_times = 0;
  1330. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1331. for (const auto & t : timings) {
  1332. uint64_t total_op_times = 0;
  1333. for (const auto & time : t.second) {
  1334. total_op_times += time;
  1335. }
  1336. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1337. << " us = " << (total_op_times / 1000.0) << " us";
  1338. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1339. auto it = flops.find(t.first);
  1340. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1341. uint64_t total_op_flops = 0;
  1342. for (const auto & elem : it->second) {
  1343. total_op_flops += elem;
  1344. }
  1345. std::cerr << " ("
  1346. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1347. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1348. << " GFLOPS/s)";
  1349. }
  1350. total_all_op_times += total_op_times;
  1351. std::cerr << std::endl;
  1352. }
  1353. if (timings.size() > 0) {
  1354. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1355. }
  1356. timings.clear();
  1357. flops.clear();
  1358. }
  1359. std::string get_node_fusion_name(const ggml_tensor * node, const char *fusion_name, uint64_t *n_flops) {
  1360. *n_flops = 0;
  1361. std::string fusion_str;
  1362. if (fusion_name) {
  1363. fusion_str = fusion_name + std::string(" ");
  1364. }
  1365. if (node->op == GGML_OP_UNARY) {
  1366. return fusion_str + ggml_unary_op_name(ggml_get_unary_op(node));
  1367. }
  1368. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1369. const uint64_t m = node->ne[0];
  1370. const uint64_t n = node->ne[1];
  1371. const uint64_t k = node->src[1]->ne[0];
  1372. const uint64_t batch = node->ne[2] * node->ne[3];
  1373. std::string name = ggml_op_name(node->op);
  1374. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1375. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1376. name += "_VEC";
  1377. }
  1378. name += " ";
  1379. name += ggml_type_name(node->src[0]->type);
  1380. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1381. if (node->op == GGML_OP_MUL_MAT_ID) {
  1382. name += " n_expert=" + std::to_string(node->src[0]->ne[2]);
  1383. }
  1384. if (batch > 1) {
  1385. name += " batch=" + std::to_string(batch);
  1386. }
  1387. name = fusion_str + name;
  1388. *n_flops = m * n * (k + (k - 1)) * batch;
  1389. return name;
  1390. }
  1391. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1392. std::string name = ggml_op_name(node->op);
  1393. ggml_tensor * knl = node->src[0];
  1394. uint64_t OW = node->ne[0];
  1395. uint64_t OH = node->ne[1];
  1396. uint64_t N = node->ne[3];
  1397. uint64_t Cout = node->ne[2];
  1398. uint64_t KW = knl->ne[0];
  1399. uint64_t KH = knl->ne[1];
  1400. uint64_t Cin = node->src[1]->ne[2];
  1401. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1402. uint64_t size_M = Cout;
  1403. uint64_t size_K = Cin * KW * KH;
  1404. uint64_t size_N = N * OW * OH;
  1405. *n_flops = size_M * size_N * (size_K + (size_K - 1));
  1406. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1407. ", N=N*OW*OH=" + std::to_string(size_N);
  1408. name = fusion_str + name;
  1409. return name;
  1410. }
  1411. if (node->op == GGML_OP_RMS_NORM) {
  1412. std::string name = ggml_op_name(node->op);
  1413. 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]) + ")";
  1414. name = fusion_str + name;
  1415. return name;
  1416. }
  1417. if (node->op == GGML_OP_FLASH_ATTN_EXT) {
  1418. const ggml_tensor * dst = node;
  1419. const ggml_tensor * q = node->src[0];
  1420. const ggml_tensor * k = node->src[1];
  1421. const ggml_tensor * v = node->src[2];
  1422. const ggml_tensor * m = node->src[3];
  1423. std::stringstream name;
  1424. name << fusion_str;
  1425. name << ggml_op_name(node->op) <<
  1426. " dst(" << dst->ne[0] << "," << dst->ne[1] << "," << dst->ne[2] << "," << dst->ne[3] << "), " <<
  1427. " q(" << q->ne[0] << "," << q->ne[1] << "," << q->ne[2] << "," << q->ne[3] << "), " <<
  1428. " k(" << k->ne[0] << "," << k->ne[1] << "," << k->ne[2] << "," << k->ne[3] << "), " <<
  1429. " v(" << v->ne[0] << "," << v->ne[1] << "," << v->ne[2] << "," << v->ne[3] << "), " <<
  1430. " m(" << (m?m->ne[0]:0) << "," << (m?m->ne[1]:0) << "," << (m?m->ne[2]:0) << "," << (m?m->ne[3]:0) << ")";
  1431. return name.str();
  1432. }
  1433. if (node->op == GGML_OP_TOP_K) {
  1434. std::stringstream name;
  1435. name << fusion_str;
  1436. name << ggml_op_name(node->op) <<
  1437. " K=" << node->ne[0] <<
  1438. " (" << node->src[0]->ne[0] << "," << node->src[0]->ne[1] << "," << node->src[0]->ne[2] << "," << node->src[0]->ne[3] << ")";
  1439. return name.str();
  1440. }
  1441. return fusion_str + ggml_op_name(node->op);
  1442. }
  1443. void log_timing(const ggml_tensor * node, const char *fusion_name, uint64_t time) {
  1444. uint64_t n_flops;
  1445. std::string name = get_node_fusion_name(node, fusion_name, &n_flops);
  1446. if (n_flops) {
  1447. flops[name].push_back(n_flops);
  1448. }
  1449. timings[name].push_back(time);
  1450. }
  1451. void log_timing(const std::vector<ggml_tensor *> &nodes, const std::vector<const char *> &names, uint64_t time) {
  1452. uint64_t total_flops = 0;
  1453. std::string name;
  1454. for (size_t n = 0; n < nodes.size(); ++n) {
  1455. uint64_t n_flops = 0;
  1456. name += get_node_fusion_name(nodes[n], names[n], &n_flops);
  1457. total_flops += n_flops;
  1458. if (n != nodes.size() - 1) {
  1459. name += ", ";
  1460. }
  1461. }
  1462. if (total_flops) {
  1463. flops[name].push_back(total_flops);
  1464. }
  1465. timings[name].push_back(time);
  1466. }
  1467. private:
  1468. std::map<std::string, std::vector<uint64_t>> timings;
  1469. std::map<std::string, std::vector<uint64_t>> flops;
  1470. uint32_t print_count {};
  1471. };
  1472. struct ggml_backend_vk_context {
  1473. std::string name;
  1474. vk_device device;
  1475. size_t semaphore_idx, event_idx;
  1476. ggml_vk_garbage_collector gc;
  1477. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1478. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging;
  1479. vk::Fence fence, almost_ready_fence;
  1480. bool submit_pending {};
  1481. bool almost_ready_fence_pending {};
  1482. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1483. // write partial sums to accumulate the square of the vector components
  1484. bool do_add_rms_partials_offset_calculation;
  1485. bool do_add_rms_partials;
  1486. uint64_t last_total_mul_mat_bytes {};
  1487. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1488. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1489. const ggml_tensor * prealloc_y_last_tensor_used {};
  1490. // Track which nodes have been used since the last sync, and whether they were written to
  1491. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1492. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1493. // Track which prealloc buffers have pending reads that need to be synchronized.
  1494. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1495. // and set to true after the buffer contents are consumed.
  1496. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1497. vk_context_ref compute_ctx;
  1498. vk_context_ref transfer_ctx;
  1499. std::vector<vk_context_ref> tensor_ctxs;
  1500. std::vector<vk::DescriptorPool> descriptor_pools;
  1501. std::vector<vk::DescriptorSet> descriptor_sets;
  1502. uint32_t descriptor_set_idx {};
  1503. uint32_t pipeline_descriptor_set_requirements {};
  1504. vk_command_pool compute_cmd_pool;
  1505. vk_command_pool transfer_cmd_pool;
  1506. // number of additional consecutive nodes that are being fused with the
  1507. // node currently being processed
  1508. int num_additional_fused_ops {};
  1509. // Bitmask of which fused ops need to write an intermediate value to memory.
  1510. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1511. // If there's no fusion, bit 0 is still set.
  1512. int fused_ops_write_mask {};
  1513. // for GGML_VK_PERF_LOGGER
  1514. std::unique_ptr<vk_perf_logger> perf_logger;
  1515. vk::QueryPool query_pool;
  1516. std::vector<const char *> query_fusion_names;
  1517. std::vector<int> query_fusion_node_count;
  1518. std::vector<ggml_tensor *> query_nodes;
  1519. std::vector<int> query_node_idx;
  1520. int32_t num_queries {};
  1521. int32_t query_idx {};
  1522. };
  1523. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1524. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1525. if (tensor->view_src) {
  1526. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1527. }
  1528. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1529. }
  1530. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  1531. {
  1532. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  1533. }
  1534. 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) {
  1535. GGML_UNUSED(p);
  1536. GGML_UNUSED(src0);
  1537. GGML_UNUSED(src1);
  1538. GGML_UNUSED(src2);
  1539. GGML_UNUSED(src3);
  1540. GGML_UNUSED(dst);
  1541. static_assert(!std::is_const<T>::value, "unexpected type");
  1542. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  1543. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  1544. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  1545. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  1546. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  1547. }
  1548. 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) {
  1549. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1550. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1551. p.b_offset = b_offset;
  1552. p.d_offset = d_offset;
  1553. GGML_UNUSED(src0);
  1554. GGML_UNUSED(src2);
  1555. GGML_UNUSED(src3);
  1556. }
  1557. 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) {
  1558. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1559. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1560. p.b_offset = b_offset;
  1561. p.d_offset = d_offset;
  1562. GGML_UNUSED(src0);
  1563. GGML_UNUSED(src2);
  1564. GGML_UNUSED(src3);
  1565. }
  1566. struct ggml_backend_vk_buffer_context {
  1567. vk_device_ref device;
  1568. vk_buffer dev_buffer;
  1569. std::string name;
  1570. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1571. device(device),
  1572. dev_buffer(dev_buffer),
  1573. name(name) {
  1574. }
  1575. ~ggml_backend_vk_buffer_context() {
  1576. ggml_vk_destroy_buffer(dev_buffer);
  1577. }
  1578. };
  1579. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1580. static std::mutex log_mutex;
  1581. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1582. std::lock_guard<std::mutex> guard(log_mutex);
  1583. vk_buffer buf = buf_ref.lock();
  1584. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1585. const std::string type = device ? "device" : "host";
  1586. allocations[buf->buffer] = size;
  1587. total_device += device ? size : 0;
  1588. total_host += device ? 0 : size;
  1589. 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));
  1590. }
  1591. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1592. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1593. return;
  1594. }
  1595. std::lock_guard<std::mutex> guard(log_mutex);
  1596. vk_buffer buf = buf_ref.lock();
  1597. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1598. std::string type = device ? "device" : "host";
  1599. auto it = allocations.find(buf->buffer);
  1600. total_device -= device ? it->second : 0;
  1601. total_host -= device ? 0 : it->second;
  1602. if (it != allocations.end()) {
  1603. 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));
  1604. allocations.erase(it);
  1605. } else {
  1606. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1607. }
  1608. }
  1609. #endif // GGML_VULKAN_MEMORY_DEBUG
  1610. struct vk_instance_t {
  1611. vk::Instance instance;
  1612. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1613. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1614. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1615. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1616. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1617. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1618. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1619. std::vector<size_t> device_indices;
  1620. std::vector<bool> device_supports_membudget;
  1621. vk_device devices[GGML_VK_MAX_DEVICES];
  1622. };
  1623. static bool vk_instance_initialized = false;
  1624. static vk_instance_t vk_instance;
  1625. #ifdef GGML_VULKAN_CHECK_RESULTS
  1626. static size_t vk_skip_checks;
  1627. static size_t vk_output_tensor;
  1628. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1629. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1630. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1631. #endif
  1632. 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);
  1633. static void ggml_backend_vk_free(ggml_backend_t backend);
  1634. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1635. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1636. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1637. return range;
  1638. }
  1639. // Wait for ctx->fence to be signaled.
  1640. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1641. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1642. // during this wait.
  1643. if (ctx->almost_ready_fence_pending) {
  1644. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1645. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1646. ctx->almost_ready_fence_pending = false;
  1647. }
  1648. // Spin (w/pause) waiting for the graph to finish executing.
  1649. vk::Result result;
  1650. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1651. if (result != vk::Result::eNotReady) {
  1652. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1653. exit(1);
  1654. }
  1655. for (uint32_t i = 0; i < 100; ++i) {
  1656. YIELD();
  1657. YIELD();
  1658. YIELD();
  1659. YIELD();
  1660. YIELD();
  1661. YIELD();
  1662. YIELD();
  1663. YIELD();
  1664. YIELD();
  1665. YIELD();
  1666. }
  1667. }
  1668. ctx->device->device.resetFences({ ctx->fence });
  1669. }
  1670. // variables to track number of compiles in progress
  1671. static uint32_t compile_count = 0;
  1672. static std::mutex compile_count_mutex;
  1673. static std::condition_variable compile_count_cond;
  1674. 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,
  1675. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1676. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1677. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1678. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1679. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1680. GGML_ASSERT(parameter_count > 0);
  1681. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1682. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1683. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1684. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1685. vk::PushConstantRange pcr(
  1686. vk::ShaderStageFlagBits::eCompute,
  1687. 0,
  1688. pipeline->push_constant_size
  1689. );
  1690. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1691. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1692. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1693. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1694. specialization_entries[i].constantID = i;
  1695. specialization_entries[i].offset = i * sizeof(uint32_t);
  1696. specialization_entries[i].size = sizeof(uint32_t);
  1697. }
  1698. vk::SpecializationInfo specialization_info(
  1699. specialization_entries.size(),
  1700. specialization_entries.data(),
  1701. specialization_constants.size() * sizeof(uint32_t),
  1702. specialization_constants.data()
  1703. );
  1704. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1705. if (device->subgroup_require_full_support && require_full_subgroups) {
  1706. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1707. }
  1708. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1709. pipeline_shader_stage_create_flags,
  1710. vk::ShaderStageFlagBits::eCompute,
  1711. pipeline->shader_module,
  1712. entrypoint.c_str(),
  1713. &specialization_info);
  1714. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1715. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1716. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1717. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1718. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1719. }
  1720. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1721. device->pipeline_executable_properties_support ?
  1722. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1723. vk::PipelineCreateFlags{},
  1724. pipeline_shader_create_info,
  1725. pipeline->layout);
  1726. vk::PipelineRobustnessCreateInfoEXT rci;
  1727. if (device->pipeline_robustness && disable_robustness) {
  1728. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1729. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1730. compute_pipeline_create_info.setPNext(&rci);
  1731. }
  1732. try {
  1733. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1734. } catch (const vk::SystemError& e) {
  1735. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1736. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1737. throw e;
  1738. }
  1739. pipeline->compiled = true;
  1740. if (vk_instance.debug_utils_support) {
  1741. vk::DebugUtilsObjectNameInfoEXT duoni;
  1742. duoni.objectType = vk::ObjectType::ePipeline;
  1743. duoni.pObjectName = pipeline->name.c_str();
  1744. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1745. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1746. }
  1747. if (device->pipeline_executable_properties_support) {
  1748. vk::PipelineExecutableInfoKHR executableInfo;
  1749. executableInfo.pipeline = pipeline->pipeline;
  1750. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1751. for (auto & s : statistics) {
  1752. // "Register Count" is reported by NVIDIA drivers.
  1753. if (strcmp(s.name, "Register Count") == 0) {
  1754. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1755. pipeline->register_count = (uint32_t)s.value.u64;
  1756. }
  1757. }
  1758. }
  1759. device->all_pipelines.push_back(pipeline);
  1760. {
  1761. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1762. assert(compile_count > 0);
  1763. compile_count--;
  1764. }
  1765. compile_count_cond.notify_all();
  1766. }
  1767. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1768. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1769. device.destroyPipelineLayout(pipeline->layout);
  1770. device.destroyShaderModule(pipeline->shader_module);
  1771. device.destroyPipeline(pipeline->pipeline);
  1772. }
  1773. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1774. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1775. ctx->pipeline_descriptor_set_requirements += n;
  1776. if (!pipeline->compiled) {
  1777. pipeline->needed = true;
  1778. ggml_vk_load_shaders(ctx->device);
  1779. }
  1780. ggml_pipeline_allocate_descriptor_sets(ctx);
  1781. }
  1782. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1783. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1784. // Enough descriptors are available
  1785. return;
  1786. }
  1787. vk_device& device = ctx->device;
  1788. // Grow by 50% to avoid frequent allocations
  1789. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1790. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1791. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1792. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1793. while (to_alloc > 0) {
  1794. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1795. to_alloc -= alloc_count;
  1796. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1797. if (pool_idx >= ctx->descriptor_pools.size()) {
  1798. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1799. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1800. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1801. }
  1802. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1803. for (uint32_t i = 0; i < alloc_count; i++) {
  1804. layouts[i] = device->dsl;
  1805. }
  1806. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1807. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1808. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1809. pool_idx++;
  1810. }
  1811. }
  1812. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1813. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1814. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1815. // Reuse command buffer
  1816. return p.cmd_buffers[p.cmd_buffer_idx++];
  1817. }
  1818. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1819. p.pool,
  1820. vk::CommandBufferLevel::ePrimary,
  1821. 1);
  1822. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1823. auto buf = cmd_buffers.front();
  1824. p.cmd_buffers.push_back(buf);
  1825. p.cmd_buffer_idx++;
  1826. return buf;
  1827. }
  1828. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1829. if (ctx->seqs.empty()) {
  1830. if (fence) {
  1831. std::lock_guard<std::mutex> guard(queue_mutex);
  1832. ctx->p->q->queue.submit({}, fence);
  1833. }
  1834. return;
  1835. }
  1836. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1837. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1838. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1839. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1840. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1841. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1842. std::vector<vk::SubmitInfo> submit_infos;
  1843. int idx = -1;
  1844. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1845. size_t reserve = 0;
  1846. for (const auto& sequence : ctx->seqs) {
  1847. reserve += sequence.size();
  1848. }
  1849. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1850. tl_wait_semaphores.reserve(reserve);
  1851. tl_wait_vals.reserve(reserve);
  1852. tl_signal_semaphores.reserve(reserve);
  1853. tl_signal_vals.reserve(reserve);
  1854. tl_submit_infos.reserve(reserve);
  1855. submit_infos.reserve(reserve);
  1856. stage_flags.reserve(reserve);
  1857. for (const auto& sequence : ctx->seqs) {
  1858. for (const auto& submission : sequence) {
  1859. stage_flags.push_back({});
  1860. idx++;
  1861. tl_wait_vals.push_back({});
  1862. tl_wait_semaphores.push_back({});
  1863. tl_signal_vals.push_back({});
  1864. tl_signal_semaphores.push_back({});
  1865. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1866. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1867. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1868. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1869. }
  1870. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1871. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1872. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1873. }
  1874. tl_submit_infos.push_back({
  1875. (uint32_t) submission.wait_semaphores.size(),
  1876. tl_wait_vals[idx].data(),
  1877. (uint32_t) submission.signal_semaphores.size(),
  1878. tl_signal_vals[idx].data(),
  1879. });
  1880. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1881. tl_submit_infos[idx].pNext = nullptr;
  1882. vk::SubmitInfo si{
  1883. (uint32_t) submission.wait_semaphores.size(),
  1884. tl_wait_semaphores[idx].data(),
  1885. stage_flags[idx].data(),
  1886. 1,
  1887. &submission.buffer,
  1888. (uint32_t) submission.signal_semaphores.size(),
  1889. tl_signal_semaphores[idx].data(),
  1890. };
  1891. si.setPNext(&tl_submit_infos[idx]);
  1892. submit_infos.push_back(si);
  1893. }
  1894. }
  1895. std::lock_guard<std::mutex> guard(queue_mutex);
  1896. ctx->p->q->queue.submit(submit_infos, fence);
  1897. ctx->seqs.clear();
  1898. }
  1899. 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) {
  1900. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1901. const uint32_t qfsize = queue_family_props.size();
  1902. // Try with avoid preferences first
  1903. for (uint32_t i = 0; i < qfsize; i++) {
  1904. 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)) {
  1905. return i;
  1906. }
  1907. }
  1908. // Fall back to only required
  1909. for (size_t i = 0; i < qfsize; i++) {
  1910. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1911. return i;
  1912. }
  1913. }
  1914. // Fall back to reusing compute queue
  1915. for (size_t i = 0; i < qfsize; i++) {
  1916. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1917. return i;
  1918. }
  1919. }
  1920. // Fall back to ignoring min_num_queries
  1921. for (size_t i = 0; i < qfsize; i++) {
  1922. if (queue_family_props[i].queueFlags & required) {
  1923. return i;
  1924. }
  1925. }
  1926. // 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.
  1927. // 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.
  1928. if (compute_index >= 0) {
  1929. return compute_index;
  1930. }
  1931. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1932. for(auto &q_family : queue_family_props) {
  1933. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1934. }
  1935. abort();
  1936. }
  1937. 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) {
  1938. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1939. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1940. q.queue_family_index = queue_family_index;
  1941. q.transfer_only = transfer_only;
  1942. q.cmd_pool.init(device, &q);
  1943. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1944. q.stage_flags = stage_flags;
  1945. }
  1946. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1947. vk_context result = std::make_shared<vk_context_struct>();
  1948. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1949. ctx->gc.contexts.emplace_back(result);
  1950. result->p = &p;
  1951. return result;
  1952. }
  1953. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1954. vk_context result = std::make_shared<vk_context_struct>();
  1955. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1956. result->p = &p;
  1957. return result;
  1958. }
  1959. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1960. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1961. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1962. vk::SemaphoreCreateInfo ci{};
  1963. ci.setPNext(&tci);
  1964. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1965. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1966. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1967. }
  1968. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1969. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1970. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1971. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1972. vk::SemaphoreCreateInfo ci{};
  1973. ci.setPNext(&tci);
  1974. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1975. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1976. }
  1977. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1978. }
  1979. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1980. if (ctx->event_idx >= ctx->gc.events.size()) {
  1981. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1982. }
  1983. return ctx->gc.events[ctx->event_idx++];
  1984. }
  1985. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1986. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1987. // Requires command buffers to be done
  1988. device->device.resetCommandPool(p.pool);
  1989. p.cmd_buffer_idx = 0;
  1990. }
  1991. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1992. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1993. // Arbitrary frequency to cleanup/reuse command buffers
  1994. static constexpr uint32_t cleanup_frequency = 10;
  1995. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1996. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1997. }
  1998. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1999. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  2000. }
  2001. }
  2002. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  2003. std::vector<uint32_t> indices;
  2004. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  2005. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  2006. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  2007. (flags & memory_type.propertyFlags) == flags &&
  2008. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  2009. indices.push_back(i);
  2010. }
  2011. }
  2012. return indices;
  2013. }
  2014. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  2015. 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]) << ")");
  2016. if (size > device->max_buffer_size) {
  2017. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  2018. }
  2019. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  2020. if (size == 0) {
  2021. buf->size = 0;
  2022. return buf;
  2023. }
  2024. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  2025. vk::MemoryAllocateFlags mem_flags {};
  2026. if (device->buffer_device_address) {
  2027. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  2028. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  2029. }
  2030. vk::BufferCreateInfo buffer_create_info{
  2031. vk::BufferCreateFlags(),
  2032. size,
  2033. usage_flags,
  2034. vk::SharingMode::eExclusive,
  2035. 0,
  2036. nullptr,
  2037. };
  2038. buf->buffer = device->device.createBuffer(buffer_create_info);
  2039. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  2040. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2041. const vk::MemoryPriorityAllocateInfoEXT mem_priority_info { 1.0f };
  2042. vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  2043. if (device->memory_priority) {
  2044. mem_flags_info.setPNext(&mem_priority_info);
  2045. }
  2046. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  2047. const auto & req_flags = *it;
  2048. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  2049. if (memory_type_indices.empty()) {
  2050. continue;
  2051. }
  2052. buf->memory_property_flags = req_flags;
  2053. bool done = false;
  2054. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  2055. try {
  2056. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  2057. done = true;
  2058. break;
  2059. } catch (const vk::SystemError& e) {
  2060. // loop and retry
  2061. // during last attempt throw the exception
  2062. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  2063. device->device.destroyBuffer(buf->buffer);
  2064. throw e;
  2065. }
  2066. }
  2067. }
  2068. if (done) {
  2069. break;
  2070. }
  2071. }
  2072. if (!buf->device_memory) {
  2073. device->device.destroyBuffer(buf->buffer);
  2074. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  2075. }
  2076. buf->ptr = nullptr;
  2077. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2078. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  2079. }
  2080. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  2081. buf->device = device;
  2082. buf->size = size;
  2083. if (device->buffer_device_address) {
  2084. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  2085. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  2086. }
  2087. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2088. device->memory_logger->log_allocation(buf, size);
  2089. #endif
  2090. return buf;
  2091. }
  2092. 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)) {
  2093. try {
  2094. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  2095. } catch (const vk::SystemError& e) {
  2096. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  2097. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2098. throw e;
  2099. }
  2100. }
  2101. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  2102. vk_buffer buf;
  2103. try {
  2104. if (device->prefer_host_memory) {
  2105. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2106. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2107. } else if (device->uma) {
  2108. // Fall back to host memory type
  2109. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2110. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2111. } else if (device->disable_host_visible_vidmem) {
  2112. if (device->allow_sysmem_fallback) {
  2113. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2114. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2115. } else {
  2116. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  2117. }
  2118. } else {
  2119. // use rebar if available, otherwise fallback to device only visible memory
  2120. if (device->allow_sysmem_fallback) {
  2121. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2122. vk::MemoryPropertyFlagBits::eDeviceLocal,
  2123. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2124. } else {
  2125. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2126. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2127. }
  2128. }
  2129. } catch (const vk::SystemError& e) {
  2130. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  2131. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2132. throw e;
  2133. }
  2134. return buf;
  2135. }
  2136. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  2137. if (buf == nullptr) {
  2138. return;
  2139. }
  2140. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2141. if (buf->device != nullptr) {
  2142. buf->device->memory_logger->log_deallocation(buf);
  2143. }
  2144. #endif
  2145. buf.reset();
  2146. }
  2147. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  2148. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  2149. }
  2150. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  2151. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  2152. const bool transfer_queue = subctx->p->q->transfer_only;
  2153. if (ctx) {
  2154. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  2155. }
  2156. subctx->s->buffer.pipelineBarrier(
  2157. subctx->p->q->stage_flags,
  2158. subctx->p->q->stage_flags,
  2159. {},
  2160. { {
  2161. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  2162. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  2163. } },
  2164. {},
  2165. {}
  2166. );
  2167. }
  2168. static void ggml_vk_set_event(vk_context& ctx, vk::Event& event) {
  2169. VK_LOG_DEBUG("ggml_vk_set_event()");
  2170. ctx->s->buffer.setEvent(
  2171. event,
  2172. ctx->p->q->stage_flags
  2173. );
  2174. }
  2175. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  2176. VK_LOG_DEBUG("ggml_vk_wait_events()");
  2177. if (events.empty()) {
  2178. return;
  2179. }
  2180. ctx->s->buffer.waitEvents(
  2181. events,
  2182. ctx->p->q->stage_flags,
  2183. ctx->p->q->stage_flags,
  2184. {},
  2185. {},
  2186. {}
  2187. );
  2188. }
  2189. // number of rows/cols for flash attention shader
  2190. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2191. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2192. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsk, uint32_t hsv, bool small_cache) {
  2193. if (hsv >= 192) {
  2194. return 2;
  2195. } else if ((hsv | hsk) & 8 || small_cache) {
  2196. return 4;
  2197. } else {
  2198. return 8;
  2199. }
  2200. }
  2201. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2202. // 128 threads split into four subgroups, each subgroup does 1/4
  2203. // of the Bc dimension.
  2204. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2205. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2206. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2207. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2208. if (path == FA_COOPMAT2) {
  2209. return flash_attention_num_small_rows;
  2210. } else {
  2211. return scalar_flash_attention_num_small_rows;
  2212. }
  2213. }
  2214. 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) {
  2215. GGML_UNUSED(clamp);
  2216. if (path == FA_SCALAR) {
  2217. if (small_rows) {
  2218. return {scalar_flash_attention_num_small_rows, 64};
  2219. } else {
  2220. if ((hsv | hsk) & 8) {
  2221. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2222. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2223. return {get_fa_scalar_num_large_rows(hsk, hsv, small_cache), 64};
  2224. } else {
  2225. return {get_fa_scalar_num_large_rows(hsk, hsv, small_cache), 32};
  2226. }
  2227. }
  2228. }
  2229. if (path == FA_COOPMAT1) {
  2230. if (small_rows) {
  2231. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2232. } else {
  2233. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2234. }
  2235. }
  2236. // small rows, large cols
  2237. if (small_rows) {
  2238. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2239. }
  2240. // small cols to reduce register count
  2241. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2242. if (hsk >= 512 || hsv >= 512) {
  2243. return {32, 32};
  2244. } else {
  2245. return {64, 32};
  2246. }
  2247. }
  2248. return {64, 64};
  2249. }
  2250. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows, bool small_cache) {
  2251. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows, small_cache)[1];
  2252. }
  2253. 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) {
  2254. uint32_t lut_size = 0;
  2255. switch (src0_type) {
  2256. case GGML_TYPE_IQ1_S:
  2257. case GGML_TYPE_IQ1_M:
  2258. lut_size = 2*2048;
  2259. break;
  2260. case GGML_TYPE_IQ2_XXS:
  2261. lut_size = 8*256;
  2262. break;
  2263. case GGML_TYPE_IQ2_XS:
  2264. lut_size = 8*512;
  2265. break;
  2266. case GGML_TYPE_IQ2_S:
  2267. lut_size = 8*1024;
  2268. break;
  2269. case GGML_TYPE_IQ3_XXS:
  2270. lut_size = 4*256;
  2271. break;
  2272. case GGML_TYPE_IQ3_S:
  2273. lut_size = 4*512;
  2274. break;
  2275. case GGML_TYPE_IQ4_NL:
  2276. case GGML_TYPE_IQ4_XS:
  2277. case GGML_TYPE_MXFP4:
  2278. lut_size = 4*16;
  2279. break;
  2280. default:
  2281. break;
  2282. }
  2283. // Needs to be kept up to date on shader changes
  2284. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2285. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2286. const uint32_t warps = warptile[0] / warptile[10];
  2287. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2288. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2289. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2290. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2291. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2292. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2293. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2294. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2295. return supported;
  2296. }
  2297. struct GpuPipelineConfig {
  2298. // GPU architecture identifier.
  2299. // Example: vk_device_architecture::AMD_GCN
  2300. vk_device_architecture arch;
  2301. // Mapping of pipeline names to their specific subgroup sizes.
  2302. // Example: {"soft_max_f32", 64}
  2303. std::unordered_map<std::string, uint32_t> pipelines;
  2304. // Default subgroup size for this GPU.
  2305. // Defaults to 0 if not explicitly provided.
  2306. uint32_t default_subgroup_size = 0;
  2307. };
  2308. // Pipeline configuration for RDNA1 GPUs.
  2309. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2310. {"soft_max", 64}, {"im2col", 64},
  2311. {"argmax", 64}, {"mul_mat_vec", 64},
  2312. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2313. };
  2314. // Pipeline configuration for RDNA2 GPUs.
  2315. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2316. {"soft_max", 64}, {"im2col", 64},
  2317. };
  2318. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2319. // Define configurations for different GPUs.
  2320. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2321. {
  2322. vk_device_architecture::AMD_RDNA1,
  2323. {
  2324. rdna1_pipelines,
  2325. },
  2326. RDNA_DEFAULT_SUBGROUP_SIZE
  2327. },
  2328. {
  2329. vk_device_architecture::AMD_RDNA2,
  2330. {
  2331. rdna2_pipelines,
  2332. },
  2333. RDNA_DEFAULT_SUBGROUP_SIZE
  2334. },
  2335. };
  2336. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2337. for (const auto &config : gpu_pipeline_configs) {
  2338. if (config.arch == arch) {
  2339. auto pipIt = config.pipelines.find(pipeline_name);
  2340. if (pipIt != config.pipelines.end()) {
  2341. return pipIt->second;
  2342. }
  2343. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2344. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2345. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2346. for (const auto &entry : sorted_pipelines) {
  2347. if (pipeline_name.find(entry.first) != std::string::npos) {
  2348. return entry.second;
  2349. }
  2350. }
  2351. return config.default_subgroup_size;
  2352. }
  2353. }
  2354. return 0; // If no matching configuration is found
  2355. }
  2356. static void ggml_vk_load_shaders(vk_device& device) {
  2357. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2358. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2359. // some shaders have a minimum subgroup size
  2360. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2361. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2362. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2363. 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;
  2364. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2365. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2366. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2367. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2368. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2369. // mulmat
  2370. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2371. l_warptile_id, m_warptile_id, s_warptile_id,
  2372. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2373. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2374. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2375. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2376. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2377. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2378. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2379. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2380. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2381. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2382. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2383. uint32_t l_align, m_align, s_align;
  2384. if (device->coopmat2) {
  2385. // spec constants and tile sizes for non-quant matmul/matmul_id
  2386. l_warptile = { 256, 128, 256, 64, 1 };
  2387. m_warptile = { 256, 128, 128, 64, 0 };
  2388. s_warptile = { 128, 64, 64, 64, 0 };
  2389. l_wg_denoms = {128, 256, 1 };
  2390. m_wg_denoms = {128, 128, 1 };
  2391. s_wg_denoms = { 64, 64, 1 };
  2392. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2393. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2394. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2395. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2396. l_mmq_wg_denoms = { 128, 256, 1 };
  2397. m_mmq_wg_denoms = { 128, 128, 1 };
  2398. s_mmq_wg_denoms = { 32, 64, 1 };
  2399. // spec constants and tile sizes for quant matmul (Qi_K)
  2400. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2401. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2402. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2403. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2404. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2405. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2406. // spec constants and tile sizes for quant matmul_id
  2407. l_warptile_mmqid = { 256, 128, 128, 32, 1, device->subgroup_size };
  2408. m_warptile_mmqid = { 256, 128, 64, 32, 0, device->subgroup_size };
  2409. s_warptile_mmqid = { 256, 128, 64, 32, 0, device->subgroup_size };
  2410. l_mmqid_wg_denoms = { 128, 128, 1 };
  2411. m_mmqid_wg_denoms = { 128, 64, 1 };
  2412. s_mmqid_wg_denoms = { 128, 64, 1 };
  2413. l_align = 128;
  2414. m_align = 64;
  2415. s_align = 32;
  2416. } else {
  2417. // Matrix cores require different warp group sizes
  2418. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2419. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2420. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2421. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2422. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2423. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2424. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2425. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2426. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2427. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2428. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2429. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2430. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2431. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2432. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2433. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2434. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2435. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2436. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2437. // K-quants use even more registers, mitigate by setting WMITER to 1
  2438. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2439. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2440. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2441. 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 };
  2442. 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 };
  2443. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2444. 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 };
  2445. 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 };
  2446. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2447. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2448. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2449. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2450. 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 };
  2451. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2452. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2453. // chip specific tuning
  2454. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2455. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2456. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2457. }
  2458. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2459. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2460. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2461. l_align = 128;
  2462. m_align = 64;
  2463. s_align = 32;
  2464. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2465. ggml_type t = (ggml_type)i;
  2466. // Disable medium and large matrix multiplication if not enough shared memory is available
  2467. // Check mmq warptiles as the largest configuration
  2468. // Throw an error if not enough for any matrix multiplication is available
  2469. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2470. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2471. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2472. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2473. device->mul_mat_m[i] = false;
  2474. device->mul_mat_l[i] = false;
  2475. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2476. device->mul_mat_l[i] = false;
  2477. }
  2478. // Disable mul_mat_id if not enough shared memory is available
  2479. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2480. device->mul_mat_id_s[i] = false;
  2481. device->mul_mat_id_m[i] = false;
  2482. device->mul_mat_id_l[i] = false;
  2483. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2484. device->mul_mat_id_m[i] = false;
  2485. device->mul_mat_id_l[i] = false;
  2486. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2487. device->mul_mat_id_l[i] = false;
  2488. }
  2489. }
  2490. }
  2491. if (!device->pipeline_matmul_f32) {
  2492. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2493. }
  2494. if (!device->pipeline_matmul_f32_f16) {
  2495. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2496. }
  2497. if (!device->pipeline_matmul_id_f32) {
  2498. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2499. }
  2500. if (!device->pipeline_matmul_bf16) {
  2501. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2502. }
  2503. if (!device->pipeline_matmul_id_bf16) {
  2504. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2505. }
  2506. std::vector<std::future<void>> compiles;
  2507. 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,
  2508. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2509. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2510. if (!require_full_subgroups && required_subgroup_size == 0) {
  2511. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2512. }
  2513. if (!pipeline) {
  2514. pipeline = std::make_shared<vk_pipeline_struct>();
  2515. }
  2516. if (!pipeline->initialized) {
  2517. pipeline->name = name;
  2518. pipeline->parameter_count = parameter_count;
  2519. pipeline->push_constant_size = push_constant_size;
  2520. pipeline->wg_denoms = wg_denoms;
  2521. pipeline->align = align;
  2522. pipeline->initialized = true;
  2523. }
  2524. if (!pipeline->needed || pipeline->compiled) {
  2525. return;
  2526. }
  2527. // TODO: We're no longer benefitting from the async compiles (shaders are
  2528. // compiled individually, as needed) and this complexity can be removed.
  2529. {
  2530. // wait until fewer than N compiles are in progress
  2531. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2532. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2533. while (compile_count >= N) {
  2534. compile_count_cond.wait(guard);
  2535. }
  2536. compile_count++;
  2537. }
  2538. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2539. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2540. };
  2541. 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,
  2542. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2543. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2544. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2545. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2546. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2547. };
  2548. 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> {
  2549. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows, small_cache)[0], 1, 1};
  2550. };
  2551. 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> {
  2552. // For large number of rows, 128 invocations seems to work best.
  2553. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2554. // can't use 256 for D==80.
  2555. // For scalar, use 128 (arbitrary)
  2556. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2557. const uint32_t D = (hsk|hsv);
  2558. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2559. ? scalar_flash_attention_workgroup_size
  2560. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2561. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows, small_cache);
  2562. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2563. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2564. const uint32_t D_lsb = D ^ (D & (D-1));
  2565. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2566. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2567. };
  2568. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2569. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2570. uint32_t HSK = fa.first.HSK; \
  2571. uint32_t HSV = fa.first.HSV; \
  2572. bool small_rows = fa.first.small_rows; \
  2573. bool small_cache = fa.first.small_cache; \
  2574. FaCodePath path = fa.first.path; \
  2575. bool aligned = fa.first.aligned; \
  2576. bool f32acc = fa.first.f32acc; \
  2577. if (path == FAPATH) { \
  2578. if (aligned) { \
  2579. if (f32acc) { \
  2580. 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)); \
  2581. } else { \
  2582. 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)); \
  2583. } \
  2584. } else { \
  2585. if (f32acc) { \
  2586. 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)); \
  2587. } else { \
  2588. 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)); \
  2589. } \
  2590. } \
  2591. } \
  2592. }
  2593. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2594. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2595. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2596. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2597. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2598. if (device->coopmat1_fa_support) {
  2599. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2600. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2601. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2602. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2603. }
  2604. #endif
  2605. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2606. if (device->coopmat2) {
  2607. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2608. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2609. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2610. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2611. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2612. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2613. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2614. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2615. }
  2616. #endif
  2617. #undef CREATE_FA
  2618. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2619. if (device->coopmat2) {
  2620. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2621. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2622. 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); \
  2623. 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); \
  2624. 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); \
  2625. 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); \
  2626. 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); \
  2627. 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); \
  2628. // Create 2 variants, {f16,f32} accumulator
  2629. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2630. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2631. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2632. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2633. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2634. if (device->coopmat_bf16_support) {
  2635. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2636. }
  2637. #endif
  2638. 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)
  2639. 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)
  2640. 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)
  2641. 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)
  2642. 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)
  2643. 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)
  2644. 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)
  2645. 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)
  2646. 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)
  2647. 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)
  2648. 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)
  2649. 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)
  2650. 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)
  2651. 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)
  2652. 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)
  2653. 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)
  2654. 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)
  2655. 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)
  2656. 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)
  2657. 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)
  2658. GGML_ASSERT(device->subgroup_ballot);
  2659. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2660. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2661. if (device->coopmat_bf16_support) {
  2662. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2663. }
  2664. #endif
  2665. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2666. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2667. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2668. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2669. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2670. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2671. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2672. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2673. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2674. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2675. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2676. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2677. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2678. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2679. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2680. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2681. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2682. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2683. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2684. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2685. #undef CREATE_MM
  2686. #undef CREATE_MM2
  2687. } else
  2688. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2689. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2690. if (device->coopmat_support) {
  2691. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2692. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2693. if (device->mul_mat ## ID ## _l[TYPE]) \
  2694. 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); \
  2695. if (device->mul_mat ## ID ## _m[TYPE]) \
  2696. 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); \
  2697. if (device->mul_mat ## ID ## _s[TYPE]) \
  2698. 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); \
  2699. if (device->mul_mat ## ID ## _l[TYPE]) \
  2700. 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); \
  2701. if (device->mul_mat ## ID ## _m[TYPE]) \
  2702. 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); \
  2703. if (device->mul_mat ## ID ## _s[TYPE]) \
  2704. 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); \
  2705. // Create 2 variants, {f16,f32} accumulator
  2706. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2707. if (device->coopmat_acc_f16_support) { \
  2708. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2709. } \
  2710. if (device->coopmat_acc_f32_support) { \
  2711. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2712. } \
  2713. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2714. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2715. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2716. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2717. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2718. if (device->coopmat_bf16_support) {
  2719. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2720. }
  2721. #endif
  2722. if (device->coopmat_acc_f16_support) {
  2723. 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, );
  2724. 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, );
  2725. 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, );
  2726. 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, );
  2727. 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, );
  2728. 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, );
  2729. 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, );
  2730. 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, );
  2731. 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, );
  2732. 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, );
  2733. 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, );
  2734. 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, );
  2735. 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, );
  2736. 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, );
  2737. 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, );
  2738. 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, );
  2739. 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, );
  2740. 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, );
  2741. 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, );
  2742. 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, );
  2743. } else {
  2744. 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, );
  2745. 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, );
  2746. 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, );
  2747. 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, );
  2748. 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, );
  2749. 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, );
  2750. 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, );
  2751. 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, );
  2752. 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, );
  2753. 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, );
  2754. 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, );
  2755. 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, );
  2756. 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, );
  2757. 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, );
  2758. 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, );
  2759. 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, );
  2760. 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, );
  2761. 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, );
  2762. 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, );
  2763. 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, );
  2764. }
  2765. GGML_ASSERT(device->subgroup_ballot);
  2766. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2767. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2768. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2769. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2770. if (device->coopmat_bf16_support) {
  2771. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2772. }
  2773. #endif
  2774. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2775. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2776. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2777. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2778. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2779. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2780. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2781. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2782. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2783. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2784. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2785. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2786. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2787. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2788. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2789. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2790. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2791. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2792. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2793. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2794. #undef CREATE_MM2
  2795. #undef CREATE_MM
  2796. } else
  2797. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2798. if (device->fp16) {
  2799. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2800. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2801. if (device->mul_mat ## ID ## _l[TYPE]) \
  2802. 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); \
  2803. if (device->mul_mat ## ID ## _m[TYPE]) \
  2804. 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); \
  2805. if (device->mul_mat ## ID ## _s[TYPE]) \
  2806. 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); \
  2807. if (device->mul_mat ## ID ## _l[TYPE]) \
  2808. 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); \
  2809. if (device->mul_mat ## ID ## _m[TYPE]) \
  2810. 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); \
  2811. if (device->mul_mat ## ID ## _s[TYPE]) \
  2812. 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); \
  2813. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2814. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2815. 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); \
  2816. } \
  2817. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2818. 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); \
  2819. } \
  2820. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2821. 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); \
  2822. } \
  2823. // Create 2 variants, {f16,f32} accumulator
  2824. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2825. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2826. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2827. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2828. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2829. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2830. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2831. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2832. 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);
  2833. 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);
  2834. 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);
  2835. 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);
  2836. 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);
  2837. 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);
  2838. 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);
  2839. 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);
  2840. 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);
  2841. 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);
  2842. 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);
  2843. 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);
  2844. 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);
  2845. 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);
  2846. 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);
  2847. 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);
  2848. 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);
  2849. 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);
  2850. 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);
  2851. 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);
  2852. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2853. if (device->integer_dot_product) {
  2854. 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);
  2855. 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);
  2856. 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);
  2857. 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);
  2858. 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);
  2859. 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);
  2860. 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);
  2861. 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);
  2862. 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);
  2863. 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);
  2864. 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);
  2865. }
  2866. #endif
  2867. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2868. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2869. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2870. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2871. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2872. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2873. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2874. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2875. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2876. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2877. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2878. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2879. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2880. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2881. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2882. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2883. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2884. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2885. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2886. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2887. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2888. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2889. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2890. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2891. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2892. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2893. if (device->integer_dot_product) {
  2894. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2895. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2896. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2897. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2898. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2899. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2900. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2901. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2902. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2903. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2904. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2905. }
  2906. #endif
  2907. } else {
  2908. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2909. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2910. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2911. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2912. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2913. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2914. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2915. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2916. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2917. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2918. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2919. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2920. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2921. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2922. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2923. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2924. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2925. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2926. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2927. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2928. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2929. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2930. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2931. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2932. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2933. if (device->integer_dot_product) {
  2934. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2935. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2936. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2937. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2938. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2939. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2940. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2941. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2942. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2943. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2944. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2945. }
  2946. #endif
  2947. }
  2948. #undef CREATE_MM2
  2949. #undef CREATE_MMQ
  2950. #undef CREATE_MM
  2951. } else {
  2952. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2953. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2954. if (device->mul_mat ## ID ## _l[TYPE]) \
  2955. 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); \
  2956. if (device->mul_mat ## ID ## _m[TYPE]) \
  2957. 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); \
  2958. if (device->mul_mat ## ID ## _s[TYPE]) \
  2959. 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); \
  2960. if (device->mul_mat ## ID ## _l[TYPE]) \
  2961. 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); \
  2962. if (device->mul_mat ## ID ## _m[TYPE]) \
  2963. 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); \
  2964. if (device->mul_mat ## ID ## _s[TYPE]) \
  2965. 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); \
  2966. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2967. if (device->mul_mat ## ID ## _l[TYPE]) \
  2968. 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); \
  2969. if (device->mul_mat ## ID ## _m[TYPE]) \
  2970. 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); \
  2971. if (device->mul_mat ## ID ## _s[TYPE]) \
  2972. 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); \
  2973. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2974. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2975. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2976. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2977. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2978. 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);
  2979. 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);
  2980. 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);
  2981. 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);
  2982. 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);
  2983. 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);
  2984. 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);
  2985. 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);
  2986. 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);
  2987. 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);
  2988. 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);
  2989. 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);
  2990. 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);
  2991. 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);
  2992. 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);
  2993. 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);
  2994. 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);
  2995. 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);
  2996. 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);
  2997. 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);
  2998. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2999. if (device->integer_dot_product) {
  3000. 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, );
  3001. 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, );
  3002. 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, );
  3003. 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, );
  3004. 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, );
  3005. 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, );
  3006. 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, );
  3007. 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, );
  3008. 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, );
  3009. 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, );
  3010. }
  3011. #endif
  3012. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  3013. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  3014. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  3015. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  3016. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  3017. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_subgroup_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3018. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_subgroup_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3019. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_subgroup_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3020. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_subgroup_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3021. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_subgroup_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3022. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_subgroup_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3023. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_subgroup_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3024. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_subgroup_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3025. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_subgroup_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3026. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_subgroup_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3027. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_subgroup_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3028. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_subgroup_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3029. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_subgroup_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3030. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_subgroup_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3031. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_subgroup_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3032. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_subgroup_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3033. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_subgroup_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3034. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_subgroup_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3035. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_subgroup_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3036. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_subgroup_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  3037. } else {
  3038. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  3039. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  3040. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  3041. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  3042. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3043. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3044. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3045. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3046. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3047. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3048. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3049. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3050. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3051. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3052. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3053. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3054. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3055. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3056. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3057. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3058. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3059. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3060. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3061. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3062. }
  3063. }
  3064. // reusing CREATE_MM from the fp32 path
  3065. if ((device->coopmat2 || device->coopmat_support)
  3066. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3067. && !device->coopmat_bf16_support
  3068. #endif
  3069. ) {
  3070. // use scalar tile sizes
  3071. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  3072. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  3073. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  3074. l_wg_denoms = {128, 128, 1 };
  3075. m_wg_denoms = { 64, 64, 1 };
  3076. s_wg_denoms = { 32, 32, 1 };
  3077. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3078. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  3079. }
  3080. #undef CREATE_MM
  3081. // mul mat vec
  3082. // the number of rows computed per shader depends on GPU model and quant
  3083. uint32_t rm_stdq = 1;
  3084. uint32_t rm_kq = 2;
  3085. uint32_t rm_stdq_int = 1;
  3086. uint32_t rm_kq_int = 1;
  3087. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3088. if (device->architecture == AMD_GCN) {
  3089. rm_stdq = 2;
  3090. rm_kq = 4;
  3091. rm_stdq_int = 4;
  3092. }
  3093. } else if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3094. rm_stdq = 2;
  3095. rm_stdq_int = 2;
  3096. }
  3097. uint32_t rm_iq = 2 * rm_kq;
  3098. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  3099. // Ensure a subgroup size >= 16 is available
  3100. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  3101. 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;
  3102. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  3103. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  3104. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  3105. static constexpr uint32_t mul_mat_vec_num_bindings = 5;
  3106. static constexpr uint32_t mul_mat_vec_id_num_bindings = 6;
  3107. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  3108. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  3109. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  3110. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3111. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3112. SHADER_REDUCTION_MODE_SHMEM;
  3113. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3114. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3115. SHADER_REDUCTION_MODE_SHMEM;
  3116. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  3117. 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);
  3118. 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);
  3119. 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);
  3120. 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);
  3121. 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);
  3122. 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);
  3123. 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);
  3124. 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);
  3125. 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);
  3126. 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);
  3127. 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);
  3128. 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);
  3129. 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);
  3130. 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);
  3131. 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);
  3132. 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);
  3133. 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);
  3134. 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);
  3135. 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);
  3136. 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);
  3137. 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);
  3138. 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);
  3139. 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);
  3140. 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);
  3141. 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);
  3142. 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);
  3143. 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);
  3144. 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);
  3145. 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);
  3146. 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);
  3147. 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);
  3148. 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);
  3149. 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);
  3150. 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);
  3151. 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);
  3152. 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);
  3153. 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);
  3154. 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);
  3155. 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);
  3156. 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);
  3157. 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);
  3158. 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);
  3159. 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);
  3160. 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);
  3161. 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);
  3162. 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);
  3163. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3164. if (device->integer_dot_product) {
  3165. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3166. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3167. 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);
  3168. 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);
  3169. 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);
  3170. 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);
  3171. 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);
  3172. 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);
  3173. 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);
  3174. 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);
  3175. 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);
  3176. 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);
  3177. 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);
  3178. }
  3179. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3180. }
  3181. 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);
  3182. 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);
  3183. 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);
  3184. 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);
  3185. 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);
  3186. 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);
  3187. 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);
  3188. 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);
  3189. 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);
  3190. 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);
  3191. 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);
  3192. 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);
  3193. 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);
  3194. 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);
  3195. 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);
  3196. 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);
  3197. 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);
  3198. 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);
  3199. 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);
  3200. 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);
  3201. 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);
  3202. 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);
  3203. 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);
  3204. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3205. if (device->integer_dot_product) {
  3206. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3207. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3208. 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);
  3209. 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);
  3210. 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);
  3211. 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);
  3212. 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);
  3213. 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);
  3214. 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);
  3215. 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);
  3216. 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);
  3217. 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);
  3218. 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);
  3219. }
  3220. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3221. }
  3222. #if !defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3223. GGML_UNUSED(rm_stdq_int);
  3224. GGML_UNUSED(rm_kq_int);
  3225. #endif
  3226. // dequant shaders
  3227. 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);
  3228. 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);
  3229. 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);
  3230. 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);
  3231. 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);
  3232. 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);
  3233. 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);
  3234. 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);
  3235. 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);
  3236. 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);
  3237. 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);
  3238. 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);
  3239. 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);
  3240. 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);
  3241. 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);
  3242. 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);
  3243. 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);
  3244. 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);
  3245. 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);
  3246. 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);
  3247. 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);
  3248. // get_rows
  3249. 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);
  3250. 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);
  3251. 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);
  3252. 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);
  3253. 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);
  3254. 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);
  3255. 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);
  3256. 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);
  3257. 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);
  3258. 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);
  3259. 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);
  3260. 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);
  3261. 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);
  3262. 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);
  3263. 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);
  3264. 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);
  3265. 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);
  3266. 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);
  3267. 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);
  3268. 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);
  3269. 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);
  3270. 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);
  3271. 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);
  3272. 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);
  3273. 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);
  3274. 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);
  3275. 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);
  3276. 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);
  3277. 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);
  3278. 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);
  3279. 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);
  3280. 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);
  3281. 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);
  3282. 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);
  3283. 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);
  3284. 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);
  3285. 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);
  3286. 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);
  3287. 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);
  3288. 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);
  3289. 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);
  3290. 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);
  3291. 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);
  3292. 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);
  3293. 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);
  3294. 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);
  3295. 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);
  3296. 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);
  3297. 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);
  3298. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3299. 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);
  3300. } else {
  3301. 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);
  3302. }
  3303. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3304. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3305. 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);
  3306. } else {
  3307. 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);
  3308. }
  3309. }
  3310. 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);
  3311. 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);
  3312. 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);
  3313. 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);
  3314. 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);
  3315. 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);
  3316. 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);
  3317. if (device->float_controls_rte_fp16 &&
  3318. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3319. 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);
  3320. 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);
  3321. }
  3322. 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);
  3323. 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);
  3324. 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);
  3325. 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);
  3326. 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);
  3327. 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);
  3328. 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);
  3329. 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);
  3330. 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);
  3331. 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);
  3332. 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);
  3333. 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);
  3334. 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);
  3335. 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);
  3336. 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);
  3337. 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);
  3338. 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);
  3339. 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);
  3340. if (device->float_controls_rte_fp16) {
  3341. 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);
  3342. 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);
  3343. 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);
  3344. 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);
  3345. 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);
  3346. 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);
  3347. } else {
  3348. 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);
  3349. 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);
  3350. 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);
  3351. 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);
  3352. 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);
  3353. 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);
  3354. }
  3355. #define SET_ROWS(itype, rte) \
  3356. 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); \
  3357. 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); \
  3358. 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); \
  3359. 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); \
  3360. 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); \
  3361. 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); \
  3362. 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); \
  3363. 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); \
  3364. 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);
  3365. if (device->float_controls_rte_fp16) {
  3366. SET_ROWS(_i32, _rte)
  3367. SET_ROWS(_i64, _rte)
  3368. } else {
  3369. SET_ROWS(_i32, )
  3370. SET_ROWS(_i64, )
  3371. }
  3372. #undef SET_ROWS
  3373. 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);
  3374. 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);
  3375. 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);
  3376. 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);
  3377. 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);
  3378. 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);
  3379. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3380. std::string s;
  3381. s += std::string(src0_f16 ? "_f16" : "_f32");
  3382. s += std::string(src1_f16 ? "_f16" : "_f32");
  3383. s += std::string(dst_f16 ? "_f16" : "_f32");
  3384. return s;
  3385. };
  3386. bool rte = device->float_controls_rte_fp16;
  3387. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3388. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3389. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3390. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3391. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3392. CREATE_BINARY(add, , {0}, 4)
  3393. CREATE_BINARY(add, _norepeat, {1}, 4)
  3394. CREATE_BINARY(sub, , {0}, 3)
  3395. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3396. CREATE_BINARY(mul, , {0}, 3)
  3397. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3398. CREATE_BINARY(div, , {0}, 3)
  3399. CREATE_BINARY(div, _norepeat, {1}, 3)
  3400. CREATE_BINARY(add_rms, , {0}, 4)
  3401. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3402. #undef CREATE_BINARY
  3403. if (device->multi_add) {
  3404. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3405. 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);
  3406. 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);
  3407. }
  3408. }
  3409. 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);
  3410. 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);
  3411. 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);
  3412. 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);
  3413. 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);
  3414. 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);
  3415. 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);
  3416. 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);
  3417. 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);
  3418. 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);
  3419. 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);
  3420. 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);
  3421. 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);
  3422. 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);
  3423. if (device->float_controls_rte_fp16) {
  3424. 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);
  3425. 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);
  3426. } else {
  3427. 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);
  3428. 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);
  3429. }
  3430. 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);
  3431. 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);
  3432. 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);
  3433. 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);
  3434. 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);
  3435. 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);
  3436. 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);
  3437. 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);
  3438. 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);
  3439. #define CREATE_UNARY(name) \
  3440. 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); \
  3441. 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);
  3442. CREATE_UNARY(gelu)
  3443. CREATE_UNARY(gelu_erf)
  3444. CREATE_UNARY(gelu_quick)
  3445. CREATE_UNARY(silu)
  3446. CREATE_UNARY(relu)
  3447. CREATE_UNARY(xielu)
  3448. CREATE_UNARY(neg)
  3449. CREATE_UNARY(tanh)
  3450. CREATE_UNARY(sigmoid)
  3451. CREATE_UNARY(hardsigmoid)
  3452. CREATE_UNARY(hardswish)
  3453. CREATE_UNARY(abs)
  3454. CREATE_UNARY(softplus)
  3455. CREATE_UNARY(step)
  3456. CREATE_UNARY(round)
  3457. CREATE_UNARY(ceil)
  3458. CREATE_UNARY(floor)
  3459. CREATE_UNARY(trunc)
  3460. #undef CREATE_UNARY
  3461. #define CREATE_UNARY_RTE(name) \
  3462. if (device->float_controls_rte_fp16) { \
  3463. 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); \
  3464. 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); \
  3465. } else { \
  3466. 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); \
  3467. 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); \
  3468. }
  3469. CREATE_UNARY_RTE(exp)
  3470. #undef CREATE_UNARY_RTE
  3471. 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);
  3472. 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);
  3473. 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);
  3474. 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);
  3475. 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);
  3476. #define CREATE_GLU(name) \
  3477. if (device->float_controls_rte_fp16) { \
  3478. 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); \
  3479. 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); \
  3480. } else { \
  3481. 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); \
  3482. 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); \
  3483. }
  3484. CREATE_GLU(geglu)
  3485. CREATE_GLU(reglu)
  3486. CREATE_GLU(swiglu)
  3487. CREATE_GLU(swiglu_oai)
  3488. CREATE_GLU(geglu_erf)
  3489. CREATE_GLU(geglu_quick)
  3490. #undef CREATE_GLU
  3491. 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);
  3492. 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);
  3493. 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);
  3494. 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);
  3495. 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);
  3496. 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);
  3497. 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);
  3498. 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);
  3499. 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);
  3500. 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);
  3501. 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);
  3502. 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);
  3503. 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);
  3504. 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);
  3505. 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);
  3506. 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);
  3507. 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);
  3508. 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);
  3509. if (device->float_controls_rte_fp16) {
  3510. 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);
  3511. 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);
  3512. 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);
  3513. 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);
  3514. 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);
  3515. 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);
  3516. 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);
  3517. } else {
  3518. 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);
  3519. 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);
  3520. 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);
  3521. 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);
  3522. 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);
  3523. 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);
  3524. 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);
  3525. }
  3526. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3527. uint32_t BLOCK_SIZE = 1u << std::min(i, device->max_workgroup_size_log2);
  3528. if (i <= device->max_workgroup_size_log2 &&
  3529. 2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3530. const uint32_t NCOLS_PADDED_LOG2 = i;
  3531. 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);
  3532. }
  3533. const uint32_t WG_UNROLL_FACTOR = BLOCK_SIZE > 1 ? 2 : 1;
  3534. BLOCK_SIZE /= WG_UNROLL_FACTOR;
  3535. 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);
  3536. }
  3537. for (uint32_t i = 0; i < num_topk_pipelines; ++i) {
  3538. const uint32_t BLOCK_SIZE = 1u << i;
  3539. const uint32_t NCOLS_PADDED_LOG2 = i;
  3540. if (i <= device->max_workgroup_size_log2) {
  3541. uint32_t nary_shmem = 2 * sizeof(int) * BLOCK_SIZE +
  3542. sizeof(int) * device->subgroup_size +
  3543. 2 * sizeof(int) +
  3544. 2 * (BLOCK_SIZE / device->subgroup_size) * sizeof(int);
  3545. if (device->subgroup_arithmetic && device->subgroup_require_full_support && device->subgroup_shuffle && device->subgroup_ballot &&
  3546. nary_shmem <= device->properties.limits.maxComputeSharedMemorySize) {
  3547. 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);
  3548. } else if (2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3549. 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);
  3550. }
  3551. }
  3552. }
  3553. 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);
  3554. 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);
  3555. ggml_vk_create_pipeline(device, device->pipeline_cumsum_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 128, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3556. 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);
  3557. for (auto &s : device->pipeline_solve_tri_f32) {
  3558. const vk_solve_tri_pipeline_state &state = s.first;
  3559. // Max number of rows to load at a time, limited by shared memory
  3560. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((state.N + state.K) * sizeof(float));
  3561. // Need at least K invocations, and prefer a minimum of 128 to spread out loading shared memory
  3562. const uint32_t block_size = std::max(128u, 1u << (uint32_t)ceilf(log2f(float(state.K))));
  3563. ggml_vk_create_pipeline(
  3564. device, s.second, "solve_tri_f32",
  3565. solve_tri_f32_len, solve_tri_f32_data, "main", 3,
  3566. sizeof(vk_op_binary_push_constants), {1, 1, 1}, { 0, state.N, state.K, batch_N, block_size }, 1, true);
  3567. }
  3568. #define IM2COL(bda) \
  3569. 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); \
  3570. 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); \
  3571. if (device->float_controls_rte_fp16) { \
  3572. 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); \
  3573. 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); \
  3574. } else { \
  3575. 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); \
  3576. 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); \
  3577. }
  3578. if (device->shader_int64 && device->buffer_device_address) {
  3579. IM2COL(_bda)
  3580. } else {
  3581. IM2COL()
  3582. }
  3583. 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);
  3584. 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);
  3585. 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);
  3586. 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);
  3587. 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);
  3588. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3589. 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);
  3590. 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);
  3591. } else {
  3592. 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);
  3593. 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);
  3594. }
  3595. 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);
  3596. 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);
  3597. 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);
  3598. // conv2d, conv_transpose_2d
  3599. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3600. uint32_t conv2d_WG_SIZE = 256;
  3601. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3602. uint32_t conv2d_TS_K = (s == CONV_SHAPE_64x32) ? 4 : 8;
  3603. uint32_t conv2d_SHMEM_PAD = 4;
  3604. vk_conv_block_size conv2d_BS = vk_conv_block_sizes[s];
  3605. bool conv2d_UNROLL = true;
  3606. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3607. if (device->coopmat2) {
  3608. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3609. }
  3610. #endif
  3611. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3612. conv2d_SHMEM_PAD = 0;
  3613. conv2d_UNROLL = false;
  3614. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3615. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3616. if (s == CONV_SHAPE_128x128 && device->architecture != vk_device_architecture::AMD_GCN) {
  3617. conv2d_UNROLL = false;
  3618. }
  3619. }
  3620. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3621. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3622. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3623. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3624. device->architecture == vk_device_architecture::AMD_GCN;
  3625. if (device->subgroup_shuffle &&
  3626. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3627. allow_collectives_nv &&
  3628. allow_collectives_amd) {
  3629. use_collectives = 1;
  3630. conv2d_BS.CRS = std::min(
  3631. device->subgroup_size,
  3632. conv2d_BS.CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3633. }
  3634. uint32_t conv2d_shmem_req =
  3635. (conv2d_BS.K * (conv2d_BS.CRS + conv2d_SHMEM_PAD) + conv2d_BS.CRS * (conv2d_BS.NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3636. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3637. conv2d_BS.CRS = 8;
  3638. if (use_collectives) {
  3639. conv2d_BS.CRS = std::min(device->subgroup_size, conv2d_BS.CRS);
  3640. }
  3641. }
  3642. std::array<uint32_t, 3> wg_denoms = { conv2d_BS.K, 1, 1 };
  3643. 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 };
  3644. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3645. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3646. const vk_conv2d_pipeline_state &state = c.first; \
  3647. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3648. spec_constants_cpy.push_back(state.s0); \
  3649. spec_constants_cpy.push_back(state.s1); \
  3650. spec_constants_cpy.push_back(state.p0); \
  3651. spec_constants_cpy.push_back(state.p1); \
  3652. spec_constants_cpy.push_back(state.d0); \
  3653. spec_constants_cpy.push_back(state.d1); \
  3654. spec_constants_cpy.push_back(state.KW); \
  3655. spec_constants_cpy.push_back(state.KH); \
  3656. ggml_vk_create_pipeline( \
  3657. device, c.second, #name #type_suffix, \
  3658. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3659. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3660. }
  3661. #define CREATE_CONVS(spv_suffix) \
  3662. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3663. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3664. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3665. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix)
  3666. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3667. if (device->coopmat2) {
  3668. CREATE_CONVS(_cm2)
  3669. } else
  3670. #endif
  3671. if (conv2d_UNROLL) {
  3672. CREATE_CONVS(_unroll)
  3673. } else {
  3674. CREATE_CONVS( )
  3675. }
  3676. #undef CREATE_CONV
  3677. #undef CREATE_CONVS
  3678. }
  3679. 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);
  3680. 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);
  3681. 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);
  3682. 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);
  3683. for (uint32_t use_push = 0; use_push < 2; ++use_push) {
  3684. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3685. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX][use_push], "topk_moe_f32_early_softmax_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 0, use_push}, 1, true, true, device->subgroup_size);
  3686. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX_NORM][use_push], "topk_moe_f32_early_softmax_norm"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 1, 0, use_push}, 1, true, true, device->subgroup_size);
  3687. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_LATE_SOFTMAX][use_push], "topk_moe_f32_late_softmax"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 1, use_push}, 1, true, true, device->subgroup_size);
  3688. }
  3689. }
  3690. for (auto &c : compiles) {
  3691. c.wait();
  3692. }
  3693. }
  3694. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3695. static vk_device ggml_vk_get_device(size_t idx) {
  3696. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3697. if (vk_instance.devices[idx] == nullptr) {
  3698. VK_LOG_DEBUG("Initializing new vk_device");
  3699. vk_device device = std::make_shared<vk_device_struct>();
  3700. vk_instance.devices[idx] = device;
  3701. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3702. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3703. #endif
  3704. size_t dev_num = vk_instance.device_indices[idx];
  3705. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3706. if (dev_num >= physical_devices.size()) {
  3707. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3708. throw std::runtime_error("Device not found");
  3709. }
  3710. device->physical_device = physical_devices[dev_num];
  3711. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3712. device->architecture = get_device_architecture(device->physical_device);
  3713. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3714. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3715. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3716. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3717. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3718. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3719. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3720. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3721. bool fp16_storage = false;
  3722. bool fp16_compute = false;
  3723. bool maintenance4_support = false;
  3724. bool sm_builtins = false;
  3725. bool amd_shader_core_properties2 = false;
  3726. bool pipeline_robustness = false;
  3727. bool coopmat2_support = false;
  3728. bool pipeline_executable_properties_support = false;
  3729. device->coopmat_support = false;
  3730. device->integer_dot_product = false;
  3731. bool bfloat16_support = false;
  3732. for (const auto& properties : ext_props) {
  3733. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3734. maintenance4_support = true;
  3735. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3736. fp16_storage = true;
  3737. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3738. fp16_compute = true;
  3739. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3740. sm_builtins = true;
  3741. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3742. amd_shader_core_properties2 = true;
  3743. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3744. pipeline_robustness = true;
  3745. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3746. device->subgroup_size_control = true;
  3747. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3748. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3749. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3750. device->coopmat_support = true;
  3751. device->coopmat_m = 0;
  3752. device->coopmat_n = 0;
  3753. device->coopmat_k = 0;
  3754. #endif
  3755. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3756. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3757. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3758. coopmat2_support = true;
  3759. #endif
  3760. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3761. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3762. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3763. device->integer_dot_product = true;
  3764. #endif
  3765. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3766. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3767. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3768. bfloat16_support = true;
  3769. #endif
  3770. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3771. pipeline_executable_properties_support = true;
  3772. } else if (strcmp("VK_EXT_memory_priority", properties.extensionName) == 0 &&
  3773. getenv("GGML_VK_ENABLE_MEMORY_PRIORITY")) {
  3774. device->memory_priority = true;
  3775. }
  3776. }
  3777. vk::PhysicalDeviceProperties2 props2;
  3778. vk::PhysicalDeviceMaintenance3Properties props3;
  3779. vk::PhysicalDeviceMaintenance4Properties props4;
  3780. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3781. vk::PhysicalDeviceDriverProperties driver_props;
  3782. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3783. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3784. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3785. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3786. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3787. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3788. props2.pNext = &props3;
  3789. props3.pNext = &subgroup_props;
  3790. subgroup_props.pNext = &driver_props;
  3791. driver_props.pNext = &vk11_props;
  3792. vk11_props.pNext = &vk12_props;
  3793. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3794. if (maintenance4_support) {
  3795. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3796. last_struct = (VkBaseOutStructure *)&props4;
  3797. }
  3798. if (sm_builtins) {
  3799. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3800. last_struct = (VkBaseOutStructure *)&sm_props;
  3801. }
  3802. if (amd_shader_core_properties2) {
  3803. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3804. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3805. }
  3806. if (device->subgroup_size_control) {
  3807. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3808. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3809. }
  3810. #if defined(VK_NV_cooperative_matrix2)
  3811. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3812. if (coopmat2_support) {
  3813. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3814. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3815. }
  3816. #endif
  3817. if (device->integer_dot_product) {
  3818. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3819. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3820. }
  3821. device->physical_device.getProperties2(&props2);
  3822. device->properties = props2.properties;
  3823. device->vendor_id = device->properties.vendorID;
  3824. device->driver_id = driver_props.driverID;
  3825. // Implementing the async backend interfaces seems broken on older Intel HW,
  3826. // see https://github.com/ggml-org/llama.cpp/issues/17302.
  3827. device->support_async = (device->vendor_id != VK_VENDOR_ID_INTEL ||
  3828. std::string(device->properties.deviceName.data()).find("(DG1)") == std::string::npos) &&
  3829. getenv("GGML_VK_DISABLE_ASYNC") == nullptr;
  3830. if (!device->support_async) {
  3831. GGML_LOG_DEBUG("ggml_vulkan: WARNING: Async execution disabled on certain Intel devices.\n");
  3832. }
  3833. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3834. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3835. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3836. } else if (maintenance4_support) {
  3837. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3838. } else {
  3839. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3840. }
  3841. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3842. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3843. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3844. } else if (maintenance4_support) {
  3845. device->max_buffer_size = props4.maxBufferSize;
  3846. } else {
  3847. device->max_buffer_size = device->max_memory_allocation_size;
  3848. }
  3849. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3850. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3851. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3852. } else {
  3853. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3854. device->suballocation_block_size = 1024*1024*1024;
  3855. }
  3856. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3857. device->subgroup_size = subgroup_props.subgroupSize;
  3858. device->subgroup_size_log2 = uint32_t(log2f(float(device->subgroup_size)));
  3859. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3860. if (sm_builtins) {
  3861. device->shader_core_count = sm_props.shaderSMCount;
  3862. } else if (amd_shader_core_properties2) {
  3863. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3864. } else {
  3865. device->shader_core_count = 0;
  3866. }
  3867. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3868. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3869. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3870. #ifdef __APPLE__
  3871. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3872. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3873. device->subgroup_arithmetic = false;
  3874. }
  3875. #endif
  3876. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3877. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3878. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3879. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3880. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3881. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3882. device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3883. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote);
  3884. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3885. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3886. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3887. device->coopmat_support = false;
  3888. }
  3889. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3890. device->max_workgroup_size_log2 = uint32_t(log2f(float(device->properties.limits.maxComputeWorkGroupInvocations)));
  3891. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3892. // Try to find a non-graphics compute queue and transfer-focused queues
  3893. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3894. 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);
  3895. const float priorities[] = { 1.0f, 1.0f };
  3896. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3897. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3898. if (compute_queue_family_index != transfer_queue_family_index) {
  3899. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3900. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3901. } else if(!device->single_queue) {
  3902. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3903. } else {
  3904. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3905. }
  3906. vk::DeviceCreateInfo device_create_info;
  3907. std::vector<const char *> device_extensions;
  3908. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3909. VkPhysicalDeviceFeatures2 device_features2;
  3910. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3911. device_features2.pNext = nullptr;
  3912. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3913. VkPhysicalDeviceVulkan11Features vk11_features;
  3914. vk11_features.pNext = nullptr;
  3915. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3916. device_features2.pNext = &vk11_features;
  3917. VkPhysicalDeviceVulkan12Features vk12_features;
  3918. vk12_features.pNext = nullptr;
  3919. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3920. vk11_features.pNext = &vk12_features;
  3921. last_struct = (VkBaseOutStructure *)&vk12_features;
  3922. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3923. pl_robustness_features.pNext = nullptr;
  3924. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3925. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3926. if (pipeline_robustness) {
  3927. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3928. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3929. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3930. }
  3931. VkPhysicalDeviceMemoryPriorityFeaturesEXT memory_priority_features;
  3932. memory_priority_features.pNext = nullptr;
  3933. memory_priority_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT;
  3934. memory_priority_features.memoryPriority = VK_FALSE;
  3935. if (device->memory_priority) {
  3936. last_struct->pNext = (VkBaseOutStructure *)&memory_priority_features;
  3937. last_struct = (VkBaseOutStructure *)&memory_priority_features;
  3938. device_extensions.push_back("VK_EXT_memory_priority");
  3939. }
  3940. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3941. subgroup_size_control_features.pNext = nullptr;
  3942. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3943. subgroup_size_control_features.computeFullSubgroups = false;
  3944. subgroup_size_control_features.subgroupSizeControl = false;
  3945. if (device->subgroup_size_control) {
  3946. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3947. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3948. }
  3949. #if defined(VK_KHR_cooperative_matrix)
  3950. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3951. coopmat_features.pNext = nullptr;
  3952. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3953. coopmat_features.cooperativeMatrix = VK_FALSE;
  3954. if (device->coopmat_support) {
  3955. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3956. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3957. }
  3958. #endif
  3959. #if defined(VK_NV_cooperative_matrix2)
  3960. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3961. coopmat2_features.pNext = nullptr;
  3962. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3963. if (coopmat2_support) {
  3964. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3965. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3966. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3967. }
  3968. #endif
  3969. #if defined(VK_KHR_shader_bfloat16)
  3970. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3971. bfloat16_features.pNext = nullptr;
  3972. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3973. if (bfloat16_support) {
  3974. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3975. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3976. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3977. }
  3978. #endif
  3979. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3980. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3981. if (maintenance4_support) {
  3982. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3983. last_struct = (VkBaseOutStructure *)&maint4_features;
  3984. device_extensions.push_back("VK_KHR_maintenance4");
  3985. }
  3986. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3987. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3988. if (device->integer_dot_product) {
  3989. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3990. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3991. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3992. }
  3993. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3994. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3995. if (pipeline_executable_properties_support) {
  3996. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3997. last_struct = (VkBaseOutStructure *)&pep_features;
  3998. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3999. }
  4000. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  4001. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  4002. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  4003. #if defined(VK_KHR_shader_bfloat16)
  4004. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4005. #else
  4006. device->bf16 = false;
  4007. #endif
  4008. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  4009. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  4010. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  4011. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  4012. device->shader_int64 = device_features2.features.shaderInt64;
  4013. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  4014. device->vulkan_memory_model = vk12_features.vulkanMemoryModel;
  4015. if (device->subgroup_size_control) {
  4016. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  4017. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  4018. device_extensions.push_back("VK_EXT_subgroup_size_control");
  4019. }
  4020. device->subgroup_size_control = device->subgroup_size_control &&
  4021. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  4022. subgroup_size_control_features.subgroupSizeControl;
  4023. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  4024. #if defined(VK_KHR_cooperative_matrix)
  4025. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  4026. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  4027. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  4028. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  4029. device->subgroup_max_size >= 32;
  4030. #endif
  4031. if (coopmat2_support) {
  4032. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4033. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  4034. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  4035. coopmat2_features.cooperativeMatrixReductions &&
  4036. coopmat2_features.cooperativeMatrixConversions &&
  4037. coopmat2_features.cooperativeMatrixPerElementOperations &&
  4038. coopmat2_features.cooperativeMatrixTensorAddressing &&
  4039. coopmat2_features.cooperativeMatrixBlockLoads &&
  4040. vk12_features.bufferDeviceAddress) {
  4041. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  4042. uint32_t count = 0;
  4043. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  4044. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  4045. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  4046. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  4047. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  4048. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  4049. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  4050. flexible_dimensions.resize(count, empty_prop);
  4051. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  4052. bool found_fp16_128 = false,
  4053. found_fp16_256 = false,
  4054. found_fp32_128 = false,
  4055. found_fp32_256 = false;
  4056. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  4057. // with 32x16x16 and 256 with 32x32x16.
  4058. for (auto &prop : flexible_dimensions) {
  4059. if (prop.saturatingAccumulation == VK_FALSE &&
  4060. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  4061. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4062. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4063. if (prop.workgroupInvocations == 128 &&
  4064. prop.MGranularity <= 32 &&
  4065. prop.NGranularity <= 16 &&
  4066. prop.KGranularity <= 16) {
  4067. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4068. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4069. found_fp16_128 = true;
  4070. }
  4071. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4072. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4073. found_fp32_128 = true;
  4074. }
  4075. }
  4076. if (prop.workgroupInvocations == 256 &&
  4077. prop.MGranularity <= 32 &&
  4078. prop.NGranularity <= 32 &&
  4079. prop.KGranularity <= 16) {
  4080. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4081. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4082. found_fp16_256 = true;
  4083. }
  4084. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4085. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4086. found_fp32_256 = true;
  4087. }
  4088. }
  4089. }
  4090. }
  4091. if (found_fp16_128 && found_fp16_256 &&
  4092. found_fp32_128 && found_fp32_256 &&
  4093. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  4094. device->coopmat2 = true;
  4095. }
  4096. }
  4097. #endif
  4098. }
  4099. if (!vk11_features.storageBuffer16BitAccess) {
  4100. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  4101. throw std::runtime_error("Unsupported device");
  4102. }
  4103. device_extensions.push_back("VK_KHR_16bit_storage");
  4104. #ifdef GGML_VULKAN_VALIDATE
  4105. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  4106. #endif
  4107. if (device->fp16) {
  4108. device_extensions.push_back("VK_KHR_shader_float16_int8");
  4109. }
  4110. #if defined(VK_KHR_cooperative_matrix)
  4111. if (device->coopmat_support) {
  4112. // Query supported shapes
  4113. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  4114. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  4115. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  4116. uint32_t cm_props_num;
  4117. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  4118. cm_props.resize(cm_props_num);
  4119. for (auto& prop : cm_props) {
  4120. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  4121. }
  4122. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  4123. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  4124. for (auto& prop : cm_props) {
  4125. 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));
  4126. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  4127. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  4128. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4129. ) {
  4130. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  4131. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  4132. // coopmat sizes not set yet
  4133. if (device->coopmat_m == 0) {
  4134. device->coopmat_acc_f32_support = true;
  4135. device->coopmat_m = prop.MSize;
  4136. device->coopmat_n = prop.NSize;
  4137. device->coopmat_k = prop.KSize;
  4138. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4139. // Only enable if shape is identical
  4140. device->coopmat_acc_f32_support = true;
  4141. }
  4142. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4143. device->coopmat_support_16x16x16_f32acc = true;
  4144. }
  4145. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  4146. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  4147. // coopmat sizes not set yet
  4148. if (device->coopmat_m == 0) {
  4149. device->coopmat_acc_f16_support = true;
  4150. device->coopmat_m = prop.MSize;
  4151. device->coopmat_n = prop.NSize;
  4152. device->coopmat_k = prop.KSize;
  4153. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4154. // Only enable if shape is identical
  4155. device->coopmat_acc_f16_support = true;
  4156. }
  4157. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4158. device->coopmat_support_16x16x16_f16acc = true;
  4159. }
  4160. }
  4161. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  4162. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  4163. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  4164. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  4165. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  4166. device->coopmat_int_m == 0
  4167. ) {
  4168. device->coopmat_int_support = true;
  4169. device->coopmat_int_m = prop.MSize;
  4170. device->coopmat_int_n = prop.NSize;
  4171. device->coopmat_int_k = prop.KSize;
  4172. }
  4173. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4174. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4175. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4176. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4177. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4178. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4179. ) {
  4180. // coopmat sizes not set yet
  4181. if (device->coopmat_m == 0) {
  4182. device->coopmat_bf16_support = true;
  4183. device->coopmat_m = prop.MSize;
  4184. device->coopmat_n = prop.NSize;
  4185. device->coopmat_k = prop.KSize;
  4186. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4187. // Only enable if shape is identical
  4188. device->coopmat_bf16_support = true;
  4189. }
  4190. }
  4191. #endif
  4192. }
  4193. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  4194. // No suitable matmul mode found
  4195. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  4196. device->coopmat_support = false;
  4197. }
  4198. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4199. device->coopmat_bf16_support = false;
  4200. }
  4201. }
  4202. if (device->coopmat_support) {
  4203. device_extensions.push_back("VK_KHR_cooperative_matrix");
  4204. }
  4205. #if defined(VK_KHR_shader_bfloat16)
  4206. if (device->coopmat_bf16_support) {
  4207. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4208. }
  4209. #endif
  4210. #endif
  4211. device->name = GGML_VK_NAME + std::to_string(idx);
  4212. device_create_info = {
  4213. vk::DeviceCreateFlags(),
  4214. device_queue_create_infos,
  4215. {},
  4216. device_extensions
  4217. };
  4218. device_create_info.setPNext(&device_features2);
  4219. device->device = device->physical_device.createDevice(device_create_info);
  4220. // Queues
  4221. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  4222. // Shaders
  4223. // Disable matmul tile sizes early if performance low or not supported
  4224. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  4225. switch (device->vendor_id) {
  4226. #ifndef GGML_VULKAN_RUN_TESTS
  4227. case VK_VENDOR_ID_AMD:
  4228. case VK_VENDOR_ID_INTEL:
  4229. device->mul_mat_l[i] = false;
  4230. device->mul_mat_m[i] = true;
  4231. device->mul_mat_s[i] = true;
  4232. device->mul_mat_id_l[i] = false;
  4233. device->mul_mat_id_m[i] = true;
  4234. device->mul_mat_id_s[i] = true;
  4235. break;
  4236. case VK_VENDOR_ID_APPLE:
  4237. device->mul_mat_l[i] = false;
  4238. device->mul_mat_m[i] = true;
  4239. device->mul_mat_s[i] = false;
  4240. device->mul_mat_id_l[i] = false;
  4241. device->mul_mat_id_m[i] = true;
  4242. device->mul_mat_id_s[i] = false;
  4243. break;
  4244. #endif
  4245. default:
  4246. device->mul_mat_l[i] = true;
  4247. device->mul_mat_m[i] = true;
  4248. device->mul_mat_s[i] = true;
  4249. device->mul_mat_id_l[i] = true;
  4250. device->mul_mat_id_m[i] = true;
  4251. device->mul_mat_id_s[i] = true;
  4252. break;
  4253. }
  4254. }
  4255. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  4256. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  4257. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  4258. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  4259. dsl_binding_flags.push_back({});
  4260. }
  4261. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  4262. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  4263. {},
  4264. dsl_binding);
  4265. descriptor_set_layout_create_info.setPNext(&dslbfci);
  4266. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  4267. ggml_vk_load_shaders(device);
  4268. if (!device->single_queue) {
  4269. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  4270. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  4271. } else {
  4272. // TODO: Use pointer or reference to avoid copy
  4273. device->transfer_queue.copyFrom(device->compute_queue);
  4274. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  4275. }
  4276. device->buffer_type = {
  4277. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4278. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  4279. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  4280. };
  4281. device->fence = device->device.createFence({});
  4282. device->idx = idx;
  4283. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  4284. device->add_rms_fusion = !device->disable_fusion &&
  4285. device->subgroup_arithmetic &&
  4286. device->vendor_id != VK_VENDOR_ID_INTEL;
  4287. device->partials_binding_alignment =
  4288. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  4289. device->mmvq_mode = 0;
  4290. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  4291. device->mmvq_mode = -1;
  4292. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  4293. device->mmvq_mode = 1;
  4294. }
  4295. return device;
  4296. }
  4297. return vk_instance.devices[idx];
  4298. }
  4299. static void ggml_vk_print_gpu_info(size_t idx) {
  4300. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4301. size_t dev_num = vk_instance.device_indices[idx];
  4302. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4303. GGML_ASSERT(vk_instance_initialized);
  4304. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4305. if (dev_num >= devices.size()) {
  4306. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4307. throw std::runtime_error("Device not found");
  4308. }
  4309. vk::PhysicalDevice physical_device = devices[dev_num];
  4310. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4311. bool fp16_storage = false;
  4312. bool fp16_compute = false;
  4313. bool coopmat_support = false;
  4314. bool coopmat2_support = false;
  4315. bool integer_dot_product = false;
  4316. bool bfloat16_support = false;
  4317. for (auto properties : ext_props) {
  4318. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4319. fp16_storage = true;
  4320. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4321. fp16_compute = true;
  4322. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4323. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4324. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4325. coopmat_support = true;
  4326. #endif
  4327. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4328. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4329. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4330. coopmat2_support = true;
  4331. #endif
  4332. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4333. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4334. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4335. integer_dot_product = true;
  4336. #endif
  4337. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4338. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4339. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4340. bfloat16_support = true;
  4341. #endif
  4342. }
  4343. }
  4344. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4345. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4346. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4347. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4348. vk::PhysicalDeviceProperties2 props2;
  4349. vk::PhysicalDeviceMaintenance3Properties props3;
  4350. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4351. vk::PhysicalDeviceDriverProperties driver_props;
  4352. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4353. props2.pNext = &props3;
  4354. props3.pNext = &subgroup_props;
  4355. subgroup_props.pNext = &driver_props;
  4356. // Pointer to the last chain element
  4357. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4358. if (integer_dot_product) {
  4359. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4360. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4361. }
  4362. physical_device.getProperties2(&props2);
  4363. VkPhysicalDeviceFeatures2 device_features2;
  4364. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4365. device_features2.pNext = nullptr;
  4366. VkPhysicalDeviceVulkan11Features vk11_features;
  4367. vk11_features.pNext = nullptr;
  4368. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4369. device_features2.pNext = &vk11_features;
  4370. VkPhysicalDeviceVulkan12Features vk12_features;
  4371. vk12_features.pNext = nullptr;
  4372. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4373. vk11_features.pNext = &vk12_features;
  4374. // Pointer to the last chain element
  4375. last_struct = (VkBaseOutStructure *)&vk12_features;
  4376. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4377. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4378. coopmat_features.pNext = nullptr;
  4379. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4380. coopmat_features.cooperativeMatrix = VK_FALSE;
  4381. if (coopmat_support) {
  4382. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4383. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4384. }
  4385. #endif
  4386. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4387. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4388. if (integer_dot_product) {
  4389. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4390. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4391. }
  4392. #if defined(VK_KHR_shader_bfloat16)
  4393. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4394. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4395. if (bfloat16_support) {
  4396. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4397. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4398. }
  4399. #endif
  4400. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4401. fp16 = fp16 && vk12_features.shaderFloat16;
  4402. #if defined(VK_KHR_shader_bfloat16)
  4403. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4404. #else
  4405. bool bf16 = false;
  4406. #endif
  4407. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4408. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4409. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4410. integer_dot_product = integer_dot_product
  4411. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4412. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4413. coopmat_support = coopmat_support
  4414. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4415. && coopmat_features.cooperativeMatrix
  4416. #endif
  4417. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4418. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4419. std::string device_name = props2.properties.deviceName.data();
  4420. 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",
  4421. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4422. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4423. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4424. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4425. }
  4426. }
  4427. static bool ggml_vk_instance_layer_settings_available();
  4428. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4429. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4430. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4431. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4432. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4433. return ggml_vk_default_dispatcher_instance;
  4434. }
  4435. static void ggml_vk_instance_init() {
  4436. if (vk_instance_initialized) {
  4437. return;
  4438. }
  4439. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4440. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4441. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4442. uint32_t api_version = vk::enumerateInstanceVersion();
  4443. if (api_version < VK_API_VERSION_1_2) {
  4444. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4445. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4446. }
  4447. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4448. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4449. const bool layer_settings = ggml_vk_instance_layer_settings_available();
  4450. #ifdef __APPLE__
  4451. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4452. #endif
  4453. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4454. std::vector<const char*> layers;
  4455. if (layer_settings) {
  4456. layers.push_back("VK_LAYER_KHRONOS_validation");
  4457. }
  4458. std::vector<const char*> extensions;
  4459. if (layer_settings) {
  4460. extensions.push_back("VK_EXT_layer_settings");
  4461. }
  4462. #ifdef __APPLE__
  4463. if (portability_enumeration_ext) {
  4464. extensions.push_back("VK_KHR_portability_enumeration");
  4465. }
  4466. #endif
  4467. if (debug_utils_ext) {
  4468. extensions.push_back("VK_EXT_debug_utils");
  4469. }
  4470. VkBool32 enable_best_practice = layer_settings;
  4471. std::vector<vk::LayerSettingEXT> settings = {
  4472. {
  4473. "VK_LAYER_KHRONOS_validation",
  4474. "validate_best_practices",
  4475. vk::LayerSettingTypeEXT::eBool32,
  4476. 1,
  4477. &enable_best_practice
  4478. },
  4479. };
  4480. vk::LayerSettingsCreateInfoEXT layer_setting_info(settings);
  4481. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions, &layer_setting_info);
  4482. #ifdef __APPLE__
  4483. if (portability_enumeration_ext) {
  4484. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4485. }
  4486. #endif
  4487. vk_instance.instance = vk::createInstance(instance_create_info);
  4488. vk_instance_initialized = true;
  4489. if (debug_utils_ext) {
  4490. vk_instance.debug_utils_support = true;
  4491. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4492. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4493. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4494. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4495. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4496. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4497. }
  4498. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4499. vk_perf_logger_concurrent = getenv("GGML_VK_PERF_LOGGER_CONCURRENT") != nullptr;
  4500. vk_enable_sync_logger = getenv("GGML_VK_SYNC_LOGGER") != nullptr;
  4501. const char* GGML_VK_PERF_LOGGER_FREQUENCY = getenv("GGML_VK_PERF_LOGGER_FREQUENCY");
  4502. if (GGML_VK_PERF_LOGGER_FREQUENCY != nullptr) {
  4503. vk_perf_logger_frequency = std::stoul(GGML_VK_PERF_LOGGER_FREQUENCY);
  4504. }
  4505. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4506. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4507. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4508. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4509. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4510. if (devices_env != nullptr) {
  4511. size_t num_available_devices = devices.size();
  4512. std::string devices(devices_env);
  4513. std::replace(devices.begin(), devices.end(), ',', ' ');
  4514. std::stringstream ss(devices);
  4515. size_t tmp;
  4516. while (ss >> tmp) {
  4517. if(tmp >= num_available_devices) {
  4518. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4519. throw std::runtime_error("Invalid Vulkan device index");
  4520. }
  4521. vk_instance.device_indices.push_back(tmp);
  4522. }
  4523. } else {
  4524. // If no vulkan devices are found, return early
  4525. if (devices.empty()) {
  4526. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4527. return;
  4528. }
  4529. // Default to using all dedicated GPUs
  4530. for (size_t i = 0; i < devices.size(); i++) {
  4531. vk::PhysicalDeviceProperties2 new_props;
  4532. vk::PhysicalDeviceDriverProperties new_driver;
  4533. vk::PhysicalDeviceIDProperties new_id;
  4534. new_props.pNext = &new_driver;
  4535. new_driver.pNext = &new_id;
  4536. devices[i].getProperties2(&new_props);
  4537. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4538. // Check if there are two physical devices corresponding to the same GPU
  4539. auto old_device = std::find_if(
  4540. vk_instance.device_indices.begin(),
  4541. vk_instance.device_indices.end(),
  4542. [&devices, &new_id](const size_t k){
  4543. vk::PhysicalDeviceProperties2 old_props;
  4544. vk::PhysicalDeviceIDProperties old_id;
  4545. old_props.pNext = &old_id;
  4546. devices[k].getProperties2(&old_props);
  4547. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4548. equals = equals || (
  4549. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4550. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4551. );
  4552. return equals;
  4553. }
  4554. );
  4555. if (old_device == vk_instance.device_indices.end()) {
  4556. vk_instance.device_indices.push_back(i);
  4557. } else {
  4558. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4559. // This can cause error when splitting layers aross the devices, need to keep only 1
  4560. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4561. vk::PhysicalDeviceProperties2 old_props;
  4562. vk::PhysicalDeviceDriverProperties old_driver;
  4563. old_props.pNext = &old_driver;
  4564. devices[*old_device].getProperties2(&old_props);
  4565. std::map<vk::DriverId, int> driver_priorities {};
  4566. int old_priority = std::numeric_limits<int>::max();
  4567. int new_priority = std::numeric_limits<int>::max();
  4568. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4569. // Smaller number -> higher priority
  4570. switch (old_props.properties.vendorID) {
  4571. case VK_VENDOR_ID_AMD:
  4572. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4573. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4574. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4575. break;
  4576. case VK_VENDOR_ID_INTEL:
  4577. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4578. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4579. break;
  4580. case VK_VENDOR_ID_NVIDIA:
  4581. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4582. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4583. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4584. #endif
  4585. break;
  4586. }
  4587. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4588. if (driver_priorities.count(old_driver.driverID)) {
  4589. old_priority = driver_priorities[old_driver.driverID];
  4590. }
  4591. if (driver_priorities.count(new_driver.driverID)) {
  4592. new_priority = driver_priorities[new_driver.driverID];
  4593. }
  4594. if (new_priority < old_priority) {
  4595. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4596. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4597. vk_instance.device_indices.push_back(i);
  4598. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4599. }
  4600. else {
  4601. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4602. }
  4603. }
  4604. }
  4605. }
  4606. // If no GPUs found, fall back to the first non-CPU device.
  4607. // If only CPU devices are available, return without devices.
  4608. if (vk_instance.device_indices.empty()) {
  4609. for (size_t i = 0; i < devices.size(); i++) {
  4610. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4611. vk_instance.device_indices.push_back(i);
  4612. break;
  4613. }
  4614. }
  4615. }
  4616. if (vk_instance.device_indices.empty()) {
  4617. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4618. return;
  4619. }
  4620. }
  4621. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4622. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4623. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4624. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4625. bool membudget_supported = false;
  4626. for (const auto & ext : extensionprops) {
  4627. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4628. membudget_supported = true;
  4629. break;
  4630. }
  4631. }
  4632. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4633. ggml_vk_print_gpu_info(i);
  4634. }
  4635. }
  4636. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4637. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4638. ggml_vk_instance_init();
  4639. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4640. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4641. ctx->device = ggml_vk_get_device(idx);
  4642. ctx->semaphore_idx = 0;
  4643. ctx->event_idx = 0;
  4644. ctx->prealloc_size_x = 0;
  4645. ctx->prealloc_size_y = 0;
  4646. ctx->prealloc_size_split_k = 0;
  4647. // Fixed size of 1KB, for deterministic behavior
  4648. ctx->prealloc_size_add_rms_partials = 1024;
  4649. ctx->fence = ctx->device->device.createFence({});
  4650. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4651. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4652. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4653. if (vk_perf_logger_enabled) {
  4654. ctx->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  4655. }
  4656. #ifdef GGML_VULKAN_CHECK_RESULTS
  4657. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4658. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4659. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4660. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4661. #endif
  4662. }
  4663. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4664. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4665. switch (type) {
  4666. case GGML_TYPE_F32:
  4667. case GGML_TYPE_Q4_0:
  4668. case GGML_TYPE_Q4_1:
  4669. case GGML_TYPE_Q5_0:
  4670. case GGML_TYPE_Q5_1:
  4671. case GGML_TYPE_Q8_0:
  4672. case GGML_TYPE_Q2_K:
  4673. case GGML_TYPE_Q3_K:
  4674. case GGML_TYPE_Q4_K:
  4675. case GGML_TYPE_Q5_K:
  4676. case GGML_TYPE_Q6_K:
  4677. case GGML_TYPE_IQ1_S:
  4678. case GGML_TYPE_IQ1_M:
  4679. case GGML_TYPE_IQ2_XXS:
  4680. case GGML_TYPE_IQ2_XS:
  4681. case GGML_TYPE_IQ2_S:
  4682. case GGML_TYPE_IQ3_XXS:
  4683. case GGML_TYPE_IQ3_S:
  4684. case GGML_TYPE_IQ4_XS:
  4685. case GGML_TYPE_IQ4_NL:
  4686. case GGML_TYPE_MXFP4:
  4687. break;
  4688. default:
  4689. return nullptr;
  4690. }
  4691. return ctx->device->pipeline_dequant[type];
  4692. }
  4693. 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) {
  4694. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4695. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4696. return ctx->device->pipeline_matmul_f32;
  4697. }
  4698. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4699. return ctx->device->pipeline_matmul_f32_f16;
  4700. }
  4701. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4702. return ctx->device->pipeline_matmul_bf16;
  4703. }
  4704. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4705. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4706. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4707. }
  4708. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4709. return ctx->device->pipeline_matmul_f16.f16acc;
  4710. }
  4711. } else {
  4712. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4713. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4714. }
  4715. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4716. return ctx->device->pipeline_matmul_f16.f32acc;
  4717. }
  4718. }
  4719. // MMQ
  4720. if (src1_type == GGML_TYPE_Q8_1) {
  4721. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4722. if (pipelines->is_empty()) {
  4723. return nullptr;
  4724. }
  4725. return pipelines;
  4726. }
  4727. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4728. return nullptr;
  4729. }
  4730. switch (src0_type) {
  4731. case GGML_TYPE_Q4_0:
  4732. case GGML_TYPE_Q4_1:
  4733. case GGML_TYPE_Q5_0:
  4734. case GGML_TYPE_Q5_1:
  4735. case GGML_TYPE_Q8_0:
  4736. case GGML_TYPE_Q2_K:
  4737. case GGML_TYPE_Q3_K:
  4738. case GGML_TYPE_Q4_K:
  4739. case GGML_TYPE_Q5_K:
  4740. case GGML_TYPE_Q6_K:
  4741. case GGML_TYPE_IQ1_S:
  4742. case GGML_TYPE_IQ1_M:
  4743. case GGML_TYPE_IQ2_XXS:
  4744. case GGML_TYPE_IQ2_XS:
  4745. case GGML_TYPE_IQ2_S:
  4746. case GGML_TYPE_IQ3_XXS:
  4747. case GGML_TYPE_IQ3_S:
  4748. case GGML_TYPE_IQ4_XS:
  4749. case GGML_TYPE_IQ4_NL:
  4750. case GGML_TYPE_MXFP4:
  4751. break;
  4752. default:
  4753. return nullptr;
  4754. }
  4755. if (ctx->device->coopmat2) {
  4756. assert(src1_type == GGML_TYPE_F16);
  4757. 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;
  4758. }
  4759. if (ctx->device->coopmat_support) {
  4760. 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;
  4761. }
  4762. 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;
  4763. }
  4764. 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) {
  4765. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4766. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4767. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4768. if (b_type == GGML_TYPE_Q8_1) {
  4769. switch (a_type) {
  4770. case GGML_TYPE_Q4_0:
  4771. case GGML_TYPE_Q4_1:
  4772. case GGML_TYPE_Q5_0:
  4773. case GGML_TYPE_Q5_1:
  4774. case GGML_TYPE_Q8_0:
  4775. case GGML_TYPE_MXFP4:
  4776. case GGML_TYPE_Q2_K:
  4777. case GGML_TYPE_Q3_K:
  4778. case GGML_TYPE_Q4_K:
  4779. case GGML_TYPE_Q5_K:
  4780. case GGML_TYPE_Q6_K:
  4781. break;
  4782. default:
  4783. return nullptr;
  4784. }
  4785. }
  4786. switch (a_type) {
  4787. case GGML_TYPE_F32:
  4788. case GGML_TYPE_F16:
  4789. case GGML_TYPE_BF16:
  4790. case GGML_TYPE_Q4_0:
  4791. case GGML_TYPE_Q4_1:
  4792. case GGML_TYPE_Q5_0:
  4793. case GGML_TYPE_Q5_1:
  4794. case GGML_TYPE_Q8_0:
  4795. case GGML_TYPE_Q2_K:
  4796. case GGML_TYPE_Q3_K:
  4797. case GGML_TYPE_Q4_K:
  4798. case GGML_TYPE_Q5_K:
  4799. case GGML_TYPE_Q6_K:
  4800. case GGML_TYPE_IQ1_S:
  4801. case GGML_TYPE_IQ1_M:
  4802. case GGML_TYPE_IQ2_XXS:
  4803. case GGML_TYPE_IQ2_XS:
  4804. case GGML_TYPE_IQ2_S:
  4805. case GGML_TYPE_IQ3_XXS:
  4806. case GGML_TYPE_IQ3_S:
  4807. case GGML_TYPE_IQ4_XS:
  4808. case GGML_TYPE_IQ4_NL:
  4809. case GGML_TYPE_MXFP4:
  4810. break;
  4811. default:
  4812. return nullptr;
  4813. }
  4814. // heuristic to choose workgroup size
  4815. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4816. 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) {
  4817. // Prefer larger workgroups when M is small, to spread the work out more
  4818. // and keep more SMs busy.
  4819. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4820. if (a_type == GGML_TYPE_Q6_K) {
  4821. if (m < 4096 && k >= 1024) {
  4822. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4823. }
  4824. } else {
  4825. if (m <= 8192 && k >= 1024) {
  4826. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4827. }
  4828. }
  4829. }
  4830. if (b_type == GGML_TYPE_Q8_1) {
  4831. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4832. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4833. }
  4834. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4835. }
  4836. 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];
  4837. }
  4838. 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) {
  4839. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4840. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4841. return ctx->device->pipeline_matmul_id_f32;
  4842. }
  4843. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4844. return ctx->device->pipeline_matmul_id_bf16;
  4845. }
  4846. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4847. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4848. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4849. }
  4850. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4851. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4852. }
  4853. } else {
  4854. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4855. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4856. }
  4857. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4858. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4859. }
  4860. }
  4861. // MMQ
  4862. if (src1_type == GGML_TYPE_Q8_1) {
  4863. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4864. if (pipelines->is_empty()) {
  4865. return nullptr;
  4866. }
  4867. return pipelines;
  4868. }
  4869. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4870. switch (src0_type) {
  4871. case GGML_TYPE_Q4_0:
  4872. case GGML_TYPE_Q4_1:
  4873. case GGML_TYPE_Q5_0:
  4874. case GGML_TYPE_Q5_1:
  4875. case GGML_TYPE_Q8_0:
  4876. case GGML_TYPE_Q2_K:
  4877. case GGML_TYPE_Q3_K:
  4878. case GGML_TYPE_Q4_K:
  4879. case GGML_TYPE_Q5_K:
  4880. case GGML_TYPE_Q6_K:
  4881. case GGML_TYPE_IQ1_S:
  4882. case GGML_TYPE_IQ1_M:
  4883. case GGML_TYPE_IQ2_XXS:
  4884. case GGML_TYPE_IQ2_XS:
  4885. case GGML_TYPE_IQ2_S:
  4886. case GGML_TYPE_IQ3_XXS:
  4887. case GGML_TYPE_IQ3_S:
  4888. case GGML_TYPE_IQ4_XS:
  4889. case GGML_TYPE_IQ4_NL:
  4890. case GGML_TYPE_MXFP4:
  4891. break;
  4892. default:
  4893. return nullptr;
  4894. }
  4895. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4896. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4897. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4898. bool support_fp16acc = !mmp.f16acc->is_empty();
  4899. bool support_fp32acc = !mmp.f32acc->is_empty();
  4900. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4901. return mmp.f16acc;
  4902. } else {
  4903. GGML_ASSERT(support_fp32acc);
  4904. return mmp.f32acc;
  4905. }
  4906. }
  4907. 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) {
  4908. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4909. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_Q8_1);
  4910. if (b_type == GGML_TYPE_Q8_1) {
  4911. switch (a_type) {
  4912. case GGML_TYPE_Q4_0:
  4913. case GGML_TYPE_Q4_1:
  4914. case GGML_TYPE_Q5_0:
  4915. case GGML_TYPE_Q5_1:
  4916. case GGML_TYPE_Q8_0:
  4917. case GGML_TYPE_MXFP4:
  4918. case GGML_TYPE_Q2_K:
  4919. case GGML_TYPE_Q3_K:
  4920. case GGML_TYPE_Q4_K:
  4921. case GGML_TYPE_Q5_K:
  4922. case GGML_TYPE_Q6_K:
  4923. break;
  4924. default:
  4925. return nullptr;
  4926. }
  4927. }
  4928. switch (a_type) {
  4929. case GGML_TYPE_F32:
  4930. case GGML_TYPE_F16:
  4931. case GGML_TYPE_BF16:
  4932. case GGML_TYPE_Q4_0:
  4933. case GGML_TYPE_Q4_1:
  4934. case GGML_TYPE_Q5_0:
  4935. case GGML_TYPE_Q5_1:
  4936. case GGML_TYPE_Q8_0:
  4937. case GGML_TYPE_Q2_K:
  4938. case GGML_TYPE_Q3_K:
  4939. case GGML_TYPE_Q4_K:
  4940. case GGML_TYPE_Q5_K:
  4941. case GGML_TYPE_Q6_K:
  4942. case GGML_TYPE_IQ1_S:
  4943. case GGML_TYPE_IQ1_M:
  4944. case GGML_TYPE_IQ2_XXS:
  4945. case GGML_TYPE_IQ2_XS:
  4946. case GGML_TYPE_IQ2_S:
  4947. case GGML_TYPE_IQ3_XXS:
  4948. case GGML_TYPE_IQ3_S:
  4949. case GGML_TYPE_IQ4_XS:
  4950. case GGML_TYPE_IQ4_NL:
  4951. case GGML_TYPE_MXFP4:
  4952. break;
  4953. default:
  4954. return nullptr;
  4955. }
  4956. // heuristic to choose workgroup size
  4957. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4958. 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) {
  4959. // Prefer larger workgroups when M is small, to spread the work out more
  4960. // and keep more SMs busy.
  4961. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4962. if (a_type == GGML_TYPE_Q6_K) {
  4963. if (m < 4096 && k >= 1024) {
  4964. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4965. }
  4966. } else {
  4967. if (m <= 8192 && k >= 1024) {
  4968. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4969. }
  4970. }
  4971. }
  4972. if (b_type == GGML_TYPE_Q8_1) {
  4973. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4974. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4975. }
  4976. return ctx->device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[dmmv_wg][a_type];
  4977. }
  4978. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[dmmv_wg][a_type];
  4979. }
  4980. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4981. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4982. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4983. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4984. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4985. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4986. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4987. size/1024.0/1024.0);
  4988. device->device.freeMemory(buf->device_memory);
  4989. device->device.destroyBuffer(buf->buffer);
  4990. return nullptr;
  4991. }
  4992. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4993. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4994. return buf->ptr;
  4995. }
  4996. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4997. if (ptr == nullptr) {
  4998. return;
  4999. }
  5000. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  5001. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5002. vk_buffer buf;
  5003. size_t index;
  5004. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  5005. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  5006. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  5007. if (ptr >= addr && ptr < endr) {
  5008. buf = std::get<2>(device->pinned_memory[i]);
  5009. index = i;
  5010. break;
  5011. }
  5012. }
  5013. if (buf == nullptr) {
  5014. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  5015. return;
  5016. }
  5017. ggml_vk_destroy_buffer(buf);
  5018. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  5019. }
  5020. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  5021. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5022. buf = nullptr;
  5023. buf_offset = 0;
  5024. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  5025. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  5026. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  5027. if (ptr >= addr && ptr < endr) {
  5028. buf = std::get<2>(device->pinned_memory[i]);
  5029. buf_offset = ((const uint8_t *)ptr) - addr;
  5030. break;
  5031. }
  5032. }
  5033. }
  5034. static vk_subbuffer ggml_vk_tensor_subbuffer(
  5035. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  5036. vk_buffer buffer = nullptr;
  5037. size_t offset = 0;
  5038. if (ctx->device->uma) {
  5039. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  5040. }
  5041. if (!buffer) {
  5042. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  5043. buffer = buf_ctx->dev_buffer;
  5044. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  5045. }
  5046. GGML_ASSERT(buffer != nullptr);
  5047. size_t size = ggml_nbytes(tensor);
  5048. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  5049. // The shader must support misaligned offsets when indexing into the buffer
  5050. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  5051. offset &= ~misalign_bytes;
  5052. size += misalign_bytes;
  5053. return vk_subbuffer{buffer, offset, size};
  5054. }
  5055. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  5056. vk_submission s;
  5057. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  5058. if (one_time) {
  5059. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  5060. } else {
  5061. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  5062. }
  5063. return s;
  5064. }
  5065. template <typename T> size_t push_constant_size(const T &t) {
  5066. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5067. GGML_UNUSED(t);
  5068. return sizeof(T);
  5069. }
  5070. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  5071. GGML_UNUSED(t);
  5072. return sizeof(T) * t.size();
  5073. }
  5074. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  5075. GGML_UNUSED(t);
  5076. return sizeof(T) * N;
  5077. }
  5078. template <typename T> const T *push_constant_data(const T &t) {
  5079. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5080. return &t;
  5081. }
  5082. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  5083. return t.data();
  5084. }
  5085. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  5086. return t.data();
  5087. }
  5088. template <typename T>
  5089. 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) {
  5090. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  5091. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  5092. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  5093. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  5094. for (auto& buffer : descriptor_buffer_infos) {
  5095. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  5096. }
  5097. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  5098. GGML_ASSERT(wg0 <= ctx->device->properties.limits.maxComputeWorkGroupCount[0] &&
  5099. wg1 <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] &&
  5100. wg2 <= ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  5101. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  5102. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  5103. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  5104. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  5105. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  5106. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  5107. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  5108. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  5109. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  5110. pipeline->layout,
  5111. 0,
  5112. { descriptor_set },
  5113. {});
  5114. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  5115. }
  5116. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  5117. s.buffer.end();
  5118. s.wait_semaphores = std::move(wait_semaphores);
  5119. s.signal_semaphores = std::move(signal_semaphores);
  5120. }
  5121. static void ggml_vk_ctx_end(vk_context& ctx) {
  5122. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  5123. if (ctx->s == nullptr) {
  5124. return;
  5125. }
  5126. ctx->s->buffer.end();
  5127. ctx->s = nullptr;
  5128. }
  5129. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  5130. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  5131. if (subctx->s != nullptr) {
  5132. ggml_vk_ctx_end(subctx);
  5133. }
  5134. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  5135. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  5136. }
  5137. static size_t ggml_vk_align_size(size_t width, size_t align) {
  5138. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  5139. return CEIL_DIV(width, align) * align;
  5140. }
  5141. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  5142. if (memcpys == nullptr) {
  5143. memcpy(dst, src, size);
  5144. } else {
  5145. memcpys->emplace_back(dst, src, size);
  5146. }
  5147. }
  5148. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  5149. if (memsets == nullptr) {
  5150. memset(dst, val, size);
  5151. } else {
  5152. memsets->emplace_back(dst, val, size);
  5153. }
  5154. }
  5155. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  5156. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  5157. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5158. ggml_vk_destroy_buffer(device->sync_staging);
  5159. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  5160. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5161. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5162. }
  5163. }
  5164. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  5165. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  5166. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5167. ggml_vk_destroy_buffer(ctx->sync_staging);
  5168. ctx->sync_staging = ggml_vk_create_buffer_check(ctx->device, size,
  5169. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5170. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5171. }
  5172. }
  5173. 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) {
  5174. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  5175. GGML_ASSERT(!ggml_is_contiguous(tensor));
  5176. // Buffer is already mapped
  5177. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5178. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5179. GGML_ABORT("fatal error");
  5180. }
  5181. // Check if src is pinned memory
  5182. vk_buffer buf = nullptr;
  5183. size_t buf_offset = 0;
  5184. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  5185. const uint64_t ne0 = tensor->ne[0];
  5186. const uint64_t ne1 = tensor->ne[1];
  5187. const uint64_t ne2 = tensor->ne[2];
  5188. const uint64_t ne3 = tensor->ne[3];
  5189. const uint64_t nb0 = tensor->nb[0];
  5190. const uint64_t nb1 = tensor->nb[1];
  5191. const uint64_t nb2 = tensor->nb[2];
  5192. const uint64_t nb3 = tensor->nb[3];
  5193. const ggml_type type = tensor->type;
  5194. const uint64_t ts = ggml_type_size(type);
  5195. const uint64_t bs = ggml_blck_size(type);
  5196. const uint64_t dstnb0 = ts;
  5197. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  5198. const uint64_t dstnb2 = dstnb1*ne1;
  5199. const uint64_t dstnb3 = dstnb2*ne2;
  5200. const uint64_t ne = ggml_nelements(tensor);
  5201. if (buf != nullptr) {
  5202. // Memory is pinned, use as staging buffer
  5203. std::vector<vk::BufferCopy> slices;
  5204. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5205. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5206. // Find longest contiguous slice
  5207. if (ne1*nb1 == dstnb2) {
  5208. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  5209. } else {
  5210. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5211. if (ne0*nb0/bs == dstnb1) {
  5212. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  5213. } else {
  5214. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5215. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5216. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5217. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  5218. }
  5219. }
  5220. }
  5221. }
  5222. }
  5223. }
  5224. ggml_vk_sync_buffers(ctx, subctx);
  5225. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5226. return;
  5227. }
  5228. if (!sync_staging) {
  5229. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5230. }
  5231. // Staging buffer required
  5232. vk_buffer& staging = ctx->device->sync_staging;
  5233. const uint64_t copy_size = ts*ne/bs;
  5234. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  5235. VkBufferCopy buf_copy{ 0, offset, copy_size };
  5236. ggml_vk_sync_buffers(ctx, subctx);
  5237. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5238. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5239. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5240. // Find longest contiguous slice
  5241. if (ne1*nb1 == dstnb2) {
  5242. 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);
  5243. } else {
  5244. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5245. if (ne0*nb0/bs == dstnb1) {
  5246. 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);
  5247. } else {
  5248. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5249. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5250. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5251. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  5252. }
  5253. }
  5254. }
  5255. }
  5256. }
  5257. }
  5258. }
  5259. 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) {
  5260. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  5261. // Check if src is pinned memory
  5262. vk_buffer buf = nullptr;
  5263. size_t buf_offset = 0;
  5264. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  5265. if (buf != nullptr) {
  5266. // Memory is pinned, use as staging buffer
  5267. std::vector<vk::BufferCopy> slices(1);
  5268. if (width == spitch) {
  5269. // Only do single write if stride is equal
  5270. slices[0].srcOffset = buf_offset;
  5271. slices[0].dstOffset = offset;
  5272. slices[0].size = width * height;
  5273. } else {
  5274. slices.resize(height);
  5275. for (size_t i = 0; i < height; i++) {
  5276. slices[i].srcOffset = buf_offset + i * spitch;
  5277. slices[i].dstOffset = offset + i * width;
  5278. slices[i].size = width;
  5279. }
  5280. }
  5281. ggml_vk_sync_buffers(nullptr, subctx);
  5282. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5283. return true;
  5284. }
  5285. VK_LOG_DEBUG("STAGING");
  5286. if (!sync_staging) {
  5287. // copy was not handled caller needs to fall back
  5288. return false;
  5289. }
  5290. // Staging buffer required
  5291. const size_t copy_size = width*height;
  5292. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  5293. vk_buffer& staging_buffer = dst->device->sync_staging;
  5294. VkBufferCopy buf_copy = {
  5295. 0,
  5296. offset,
  5297. copy_size};
  5298. ggml_vk_sync_buffers(nullptr, subctx);
  5299. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5300. if (width == spitch) {
  5301. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  5302. } else {
  5303. for (size_t i = 0; i < height; i++) {
  5304. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  5305. }
  5306. }
  5307. return true;
  5308. }
  5309. 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) {
  5310. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  5311. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  5312. }
  5313. 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) {
  5314. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  5315. // Buffer is already mapped
  5316. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5317. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5318. for (size_t i = 0; i < height; i++) {
  5319. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  5320. }
  5321. } else {
  5322. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5323. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5324. ggml_vk_ctx_begin(dst->device, subctx);
  5325. bool ret = ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  5326. GGML_ASSERT(ret);
  5327. ggml_vk_ctx_end(subctx);
  5328. for (auto& cpy : subctx->in_memcpys) {
  5329. memcpy(cpy.dst, cpy.src, cpy.n);
  5330. }
  5331. for (auto& mset : subctx->memsets) {
  5332. memset(mset.dst, mset.val, mset.n);
  5333. }
  5334. ggml_vk_submit(subctx, dst->device->fence);
  5335. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  5336. dst->device->device.resetFences({ dst->device->fence });
  5337. ggml_vk_queue_command_pools_cleanup(dst->device);
  5338. }
  5339. }
  5340. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  5341. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  5342. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  5343. }
  5344. 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) {
  5345. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  5346. GGML_ASSERT(width > 0);
  5347. GGML_ASSERT(height > 0);
  5348. GGML_ASSERT(src != nullptr);
  5349. // TODO: staging_offset is not used
  5350. // Check if dst is pinned memory
  5351. vk_buffer buf = nullptr;
  5352. size_t buf_offset = 0;
  5353. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  5354. std::vector<vk::BufferCopy> slices(1);
  5355. if (width == spitch && width == dpitch) {
  5356. // Only do single write if stride is equal
  5357. slices[0].srcOffset = offset;
  5358. slices[0].dstOffset = buf_offset;
  5359. slices[0].size = width * height;
  5360. } else {
  5361. slices.resize(height);
  5362. for (size_t i = 0; i < height; i++) {
  5363. slices[i].srcOffset = offset + i * spitch;
  5364. slices[i].dstOffset = buf_offset + i * dpitch;
  5365. slices[i].size = width;
  5366. }
  5367. }
  5368. if (buf != nullptr) {
  5369. // Memory is pinned, use as staging buffer
  5370. ggml_vk_sync_buffers(nullptr, subctx);
  5371. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5372. return true;
  5373. }
  5374. VK_LOG_DEBUG("STAGING");
  5375. if (!sync_staging) {
  5376. // copy was not handled caller needs to fall back
  5377. return false;
  5378. }
  5379. // Fall back to staging buffer
  5380. const size_t copy_size = dpitch * height;
  5381. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5382. vk_buffer& staging_buffer = src->device->sync_staging;
  5383. ggml_vk_sync_buffers(nullptr, subctx);
  5384. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5385. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5386. return true;
  5387. }
  5388. 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) {
  5389. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5390. }
  5391. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5392. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5393. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5394. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5395. // the HW device to host copy path.
  5396. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5397. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5398. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5399. } else {
  5400. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5401. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5402. ggml_vk_ctx_begin(src->device, subctx);
  5403. bool ret = ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5404. GGML_ASSERT(ret);
  5405. ggml_vk_ctx_end(subctx);
  5406. ggml_vk_submit(subctx, src->device->fence);
  5407. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5408. src->device->device.resetFences({ src->device->fence });
  5409. ggml_vk_queue_command_pools_cleanup(src->device);
  5410. for (auto& cpy : subctx->out_memcpys) {
  5411. memcpy(cpy.dst, cpy.src, cpy.n);
  5412. }
  5413. }
  5414. }
  5415. 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) {
  5416. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5417. // Make sure both buffers are on same device
  5418. GGML_ASSERT(src->device == dst->device);
  5419. VkBufferCopy bc{ src_offset, dst_offset, size };
  5420. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5421. }
  5422. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5423. if (src->device == dst->device) {
  5424. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5425. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5426. // Copy within the device
  5427. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5428. ggml_vk_ctx_begin(src->device, subctx);
  5429. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5430. ggml_vk_ctx_end(subctx);
  5431. ggml_vk_submit(subctx, src->device->fence);
  5432. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5433. src->device->device.resetFences({ src->device->fence });
  5434. ggml_vk_queue_command_pools_cleanup(src->device);
  5435. } else {
  5436. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5437. // Copy device to device
  5438. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5439. // Copy to src staging buffer
  5440. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5441. // Copy to dst buffer
  5442. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5443. }
  5444. }
  5445. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5446. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5447. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5448. dst->device->uma) {
  5449. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5450. return;
  5451. }
  5452. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5453. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5454. }
  5455. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5456. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5457. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5458. dst->device->uma) {
  5459. memset((uint8_t*)dst->ptr + offset, c, size);
  5460. return;
  5461. }
  5462. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5463. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5464. ggml_vk_ctx_begin(dst->device, subctx);
  5465. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5466. ggml_vk_ctx_end(subctx);
  5467. ggml_vk_submit(subctx, dst->device->fence);
  5468. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5469. dst->device->device.resetFences({ dst->device->fence });
  5470. ggml_vk_queue_command_pools_cleanup(dst->device);
  5471. }
  5472. 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) {
  5473. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5474. if (disable_split_k) {
  5475. return 1;
  5476. }
  5477. uint32_t split_k = 1;
  5478. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5479. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5480. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5481. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5482. if (k >= 2048) {
  5483. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5484. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5485. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5486. split_k = 3;
  5487. }
  5488. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5489. split_k = std::min(split_k, 8u);
  5490. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5491. // If this rounded up size would cause the last split to be empty,
  5492. // then reduce the split count.
  5493. while (true) {
  5494. if (split_k == 1) {
  5495. break;
  5496. }
  5497. uint32_t k_split = CEIL_DIV(k, split_k);
  5498. k_split = ROUNDUP_POW2(k_split, 256);
  5499. if (k_split * (split_k - 1) < k) {
  5500. break;
  5501. }
  5502. split_k--;
  5503. }
  5504. }
  5505. }
  5506. return split_k;
  5507. }
  5508. 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) {
  5509. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5510. if (ctx->device->coopmat2) {
  5511. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5512. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5513. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5514. // Use large shader when the N dimension is greater than the medium shader's tile size
  5515. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5516. // Prefer large over medium if either:
  5517. // - medium or large tiles would overfill the GPU
  5518. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5519. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5520. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5521. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5522. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5523. 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])) {
  5524. return aligned ? mmp->a_l : mmp->l;
  5525. }
  5526. // Use medium shader when the N dimension is greater than the small shader's tile size
  5527. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5528. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5529. return aligned ? mmp->a_m : mmp->m;
  5530. }
  5531. return aligned ? mmp->a_s : mmp->s;
  5532. }
  5533. 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])) {
  5534. return aligned ? mmp->a_s : mmp->s;
  5535. }
  5536. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5537. return aligned ? mmp->a_m : mmp->m;
  5538. }
  5539. return aligned ? mmp->a_l : mmp->l;
  5540. GGML_UNUSED(src1_type);
  5541. }
  5542. 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) {
  5543. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5544. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5545. }
  5546. static void ggml_vk_matmul(
  5547. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5548. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5549. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5550. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5551. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5552. uint32_t padded_n) {
  5553. 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 << ")");
  5554. if (split_k == 1) {
  5555. 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 };
  5556. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5557. return;
  5558. }
  5559. if (ctx->prealloc_split_k_need_sync) {
  5560. ggml_vk_sync_buffers(ctx, subctx);
  5561. }
  5562. GGML_ASSERT(batch_stride_d == m * n);
  5563. // Round the split size up to a multiple of 256 (k-quant alignment)
  5564. uint32_t k_split = CEIL_DIV(k, split_k);
  5565. k_split = ROUNDUP_POW2(k_split, 256);
  5566. 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 };
  5567. // Make sure enough workgroups get assigned for split k to work
  5568. 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 });
  5569. ggml_vk_sync_buffers(ctx, subctx);
  5570. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5571. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5572. ctx->prealloc_split_k_need_sync = true;
  5573. }
  5574. 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) {
  5575. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5576. if (ctx->device->coopmat2) {
  5577. // Use large shader when the N dimension is greater than the medium shader's tile size
  5578. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5579. 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])) {
  5580. return aligned ? mmp->a_l : mmp->l;
  5581. }
  5582. // Use medium shader when the N dimension is greater than the small shader's tile size
  5583. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5584. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5585. return aligned ? mmp->a_m : mmp->m;
  5586. }
  5587. return aligned ? mmp->a_s : mmp->s;
  5588. }
  5589. 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])) {
  5590. return aligned ? mmp->a_s : mmp->s;
  5591. }
  5592. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5593. return aligned ? mmp->a_m : mmp->m;
  5594. }
  5595. return aligned ? mmp->a_l : mmp->l;
  5596. }
  5597. 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) {
  5598. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5599. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5600. }
  5601. static void ggml_vk_matmul_id(
  5602. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5603. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5604. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5605. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5606. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5607. uint32_t padded_n) {
  5608. 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 << "), " <<
  5609. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5610. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5611. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5612. 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,
  5613. nei0, nei1, nbi1, ne11, padded_n };
  5614. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5615. }
  5616. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5617. return
  5618. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5619. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5620. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5621. }
  5622. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5623. // Choose "contiguous copy" shader if src/dst are contiguous
  5624. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5625. // Use optimized "transpose" shader if src dim1 is the innermost dimension.
  5626. bool transpose = dst && src->nb[1] == ggml_type_size(to) && ggml_are_same_shape(dst, src);
  5627. if (transpose && src->type == to) {
  5628. if (ggml_type_size(to) == 4) {
  5629. return ctx->device->pipeline_cpy_transpose_32;
  5630. } else if (ggml_type_size(to) == 2) {
  5631. return ctx->device->pipeline_cpy_transpose_16;
  5632. }
  5633. }
  5634. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5635. if (contig) {
  5636. return ctx->device->pipeline_contig_cpy_f32_f32;
  5637. } else {
  5638. return ctx->device->pipeline_cpy_f32_f32;
  5639. }
  5640. }
  5641. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5642. if (contig) {
  5643. return ctx->device->pipeline_contig_cpy_f32_f16;
  5644. } else {
  5645. return ctx->device->pipeline_cpy_f32_f16;
  5646. }
  5647. }
  5648. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5649. if (contig) {
  5650. return ctx->device->pipeline_contig_cpy_f16_f16;
  5651. } else {
  5652. return ctx->device->pipeline_cpy_f16_f16;
  5653. }
  5654. }
  5655. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5656. if (contig) {
  5657. return ctx->device->pipeline_contig_cpy_f16_f32;
  5658. } else {
  5659. return ctx->device->pipeline_cpy_f16_f32;
  5660. }
  5661. }
  5662. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5663. if (contig) {
  5664. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5665. } else {
  5666. return ctx->device->pipeline_cpy_f32_bf16;
  5667. }
  5668. }
  5669. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5670. if (contig) {
  5671. return ctx->device->pipeline_contig_cpy_f32_i32;
  5672. } else {
  5673. return ctx->device->pipeline_cpy_f32_i32;
  5674. }
  5675. }
  5676. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5677. if (contig) {
  5678. return ctx->device->pipeline_contig_cpy_i32_f32;
  5679. } else {
  5680. return ctx->device->pipeline_cpy_i32_f32;
  5681. }
  5682. }
  5683. if (src->type == GGML_TYPE_F32) {
  5684. switch (to) {
  5685. case GGML_TYPE_Q4_0:
  5686. case GGML_TYPE_Q4_1:
  5687. case GGML_TYPE_Q5_0:
  5688. case GGML_TYPE_Q5_1:
  5689. case GGML_TYPE_Q8_0:
  5690. case GGML_TYPE_IQ4_NL:
  5691. return ctx->device->pipeline_cpy_f32_quant[to];
  5692. default:
  5693. break;
  5694. }
  5695. }
  5696. if (to == GGML_TYPE_F32) {
  5697. switch (src->type) {
  5698. case GGML_TYPE_Q4_0:
  5699. case GGML_TYPE_Q4_1:
  5700. case GGML_TYPE_Q5_0:
  5701. case GGML_TYPE_Q5_1:
  5702. case GGML_TYPE_Q8_0:
  5703. case GGML_TYPE_IQ4_NL:
  5704. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5705. default:
  5706. break;
  5707. }
  5708. }
  5709. if (src->type == to) {
  5710. // Copy two or four bytes at a time, depending on block size.
  5711. // For quantized types, we scale by block size/type size. But
  5712. // this path is also used for bf16->bf16 for example, where the
  5713. // type size must be exactly 2 or 4.
  5714. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5715. if ((ggml_type_size(src->type) % 4) == 0) {
  5716. if (contig) {
  5717. return ctx->device->pipeline_contig_cpy_f32_f32;
  5718. } else {
  5719. return ctx->device->pipeline_cpy_f32_f32;
  5720. }
  5721. } else {
  5722. if (contig) {
  5723. return ctx->device->pipeline_contig_cpy_f16_f16;
  5724. } else {
  5725. return ctx->device->pipeline_cpy_f16_f16;
  5726. }
  5727. }
  5728. }
  5729. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5730. GGML_ABORT("fatal error");
  5731. }
  5732. 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) {
  5733. 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] << "), ";
  5734. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5735. const int tensor_type_size = ggml_type_size(tensor->type);
  5736. const uint32_t ne = ggml_nelements(tensor);
  5737. std::array<uint32_t, 3> elements;
  5738. if (ne > 262144) {
  5739. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5740. } else if (ne > 512) {
  5741. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5742. } else {
  5743. elements = { ne, 1, 1 };
  5744. }
  5745. vk_op_unary_push_constants pc = {
  5746. (uint32_t)ne,
  5747. (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,
  5748. (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]),
  5749. 0,
  5750. 0.0f, 0.0f,
  5751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5752. };
  5753. init_pushconst_fastdiv(pc);
  5754. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5755. ggml_vk_sync_buffers(ctx, subctx);
  5756. }
  5757. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5758. switch(type) {
  5759. case GGML_TYPE_Q8_1:
  5760. return ctx->device->pipeline_quantize_q8_1_x4;
  5761. default:
  5762. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5763. GGML_ABORT("fatal error");
  5764. }
  5765. }
  5766. 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) {
  5767. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5768. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5769. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5770. ggml_vk_sync_buffers(ctx, subctx);
  5771. }
  5772. 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) {
  5773. 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];
  5774. 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];
  5775. 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];
  5776. std::cerr << "))");
  5777. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5778. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5779. const uint64_t ne00 = src0->ne[0];
  5780. const uint64_t ne01 = src0->ne[1];
  5781. const uint64_t ne02 = src0->ne[2];
  5782. const uint64_t ne03 = src0->ne[3];
  5783. const uint64_t ne10 = src1->ne[0];
  5784. const uint64_t ne11 = src1->ne[1];
  5785. const uint64_t ne12 = src1->ne[2];
  5786. const uint64_t ne13 = src1->ne[3];
  5787. const uint64_t ne21 = dst->ne[1];
  5788. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5789. const uint32_t stride_batch_d = stride_d*ne21;
  5790. const uint64_t r2 = ne12 / ne02;
  5791. const uint64_t r3 = ne13 / ne03;
  5792. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5793. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5794. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5795. vk_buffer d_Qx = nullptr;
  5796. size_t qx_buf_offset = 0;
  5797. vk_buffer d_Qy = nullptr;
  5798. size_t qy_buf_offset = 0;
  5799. bool src0_uma = false;
  5800. bool src1_uma = false;
  5801. if (ctx->device->uma) {
  5802. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5803. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5804. src0_uma = d_Qx != nullptr;
  5805. src1_uma = d_Qy != nullptr;
  5806. }
  5807. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5808. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5809. !ggml_vk_dim01_contiguous(src0);
  5810. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5811. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5812. !ggml_vk_dim01_contiguous(src1);
  5813. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5814. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5815. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5816. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  5817. // Check for mmq first
  5818. 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;
  5819. if (mmp == nullptr) {
  5820. // Fall back to f16 dequant mul mat
  5821. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5822. quantize_y = false;
  5823. }
  5824. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5825. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5826. if (qx_needs_dequant) {
  5827. // Fall back to dequant + f16 mulmat
  5828. 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]);
  5829. }
  5830. // Not implemented
  5831. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5832. 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)));
  5833. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5834. 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));
  5835. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5836. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5837. const uint64_t x_ne = ggml_nelements(src0);
  5838. // 128 elements per Q8_1 x4 block
  5839. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  5840. const uint64_t d_ne = ggml_nelements(dst);
  5841. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5842. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5843. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5844. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5845. 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);
  5846. const uint64_t d_sz = sizeof(float) * d_ne;
  5847. vk_pipeline to_fp16_vk_0 = nullptr;
  5848. vk_pipeline to_fp16_vk_1 = nullptr;
  5849. vk_pipeline to_q8_1 = nullptr;
  5850. if (x_non_contig) {
  5851. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5852. } else {
  5853. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5854. }
  5855. if (y_non_contig) {
  5856. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5857. } else {
  5858. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5859. }
  5860. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5861. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5862. if (quantize_y) {
  5863. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5864. }
  5865. {
  5866. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  5867. if (
  5868. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5869. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5870. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5871. GGML_ABORT("Requested preallocation size is too large");
  5872. }
  5873. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5874. ctx->prealloc_size_x = x_sz;
  5875. ggml_vk_preallocate_buffers(ctx, subctx);
  5876. }
  5877. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5878. ctx->prealloc_size_y = y_sz;
  5879. ggml_vk_preallocate_buffers(ctx, subctx);
  5880. }
  5881. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5882. ctx->prealloc_size_split_k = split_k_size;
  5883. ggml_vk_preallocate_buffers(ctx, subctx);
  5884. }
  5885. // Request descriptor sets
  5886. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5887. if (qx_needs_dequant) {
  5888. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5889. }
  5890. if (qy_needs_dequant) {
  5891. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5892. }
  5893. if (quantize_y) {
  5894. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5895. }
  5896. if (split_k > 1) {
  5897. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5898. }
  5899. }
  5900. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5901. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5902. GGML_ASSERT(d_D != nullptr);
  5903. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  5904. vk_buffer d_X;
  5905. uint64_t x_buf_offset = 0;
  5906. vk_buffer d_Y;
  5907. uint64_t y_buf_offset = 0;
  5908. if (!src0_uma) {
  5909. d_Qx = src0_buf_ctx->dev_buffer;
  5910. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5911. GGML_ASSERT(d_Qx != nullptr);
  5912. }
  5913. if (!src1_uma) {
  5914. d_Qy = src1_buf_ctx->dev_buffer;
  5915. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5916. GGML_ASSERT(d_Qy != nullptr);
  5917. }
  5918. if (qx_needs_dequant) {
  5919. d_X = ctx->prealloc_x;
  5920. GGML_ASSERT(d_X->size >= x_sz);
  5921. } else {
  5922. d_X = d_Qx;
  5923. x_buf_offset = qx_buf_offset;
  5924. GGML_ASSERT(qx_sz == x_sz);
  5925. }
  5926. if (qy_needs_dequant) {
  5927. d_Y = ctx->prealloc_y;
  5928. GGML_ASSERT(d_Y->size >= y_sz);
  5929. } else if (quantize_y) {
  5930. d_Y = ctx->prealloc_y;
  5931. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  5932. } else {
  5933. d_Y = d_Qy;
  5934. y_buf_offset = qy_buf_offset;
  5935. GGML_ASSERT(qy_sz == y_sz);
  5936. }
  5937. if (x_non_contig || qx_needs_dequant) {
  5938. if (ctx->prealloc_x_need_sync) {
  5939. ggml_vk_sync_buffers(ctx, subctx);
  5940. }
  5941. }
  5942. if (x_non_contig) {
  5943. 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));
  5944. } else if (qx_needs_dequant) {
  5945. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5946. 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});
  5947. ggml_vk_sync_buffers(ctx, subctx);
  5948. }
  5949. if (y_non_contig) {
  5950. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5951. ctx->prealloc_y_last_tensor_used != src1) {
  5952. if (ctx->prealloc_y_need_sync) {
  5953. ggml_vk_sync_buffers(ctx, subctx);
  5954. }
  5955. 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));
  5956. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5957. ctx->prealloc_y_last_tensor_used = src1;
  5958. }
  5959. }
  5960. if (quantize_y) {
  5961. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5962. ctx->prealloc_y_last_tensor_used != src1) {
  5963. if (ctx->prealloc_y_need_sync) {
  5964. ggml_vk_sync_buffers(ctx, subctx);
  5965. }
  5966. 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);
  5967. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5968. ctx->prealloc_y_last_tensor_used = src1;
  5969. }
  5970. }
  5971. uint32_t stride_batch_x = ne00*ne01;
  5972. uint32_t stride_batch_y = ne10*ne11;
  5973. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5974. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5975. }
  5976. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5977. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5978. }
  5979. // compute
  5980. ggml_vk_matmul(
  5981. ctx, subctx, pipeline,
  5982. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  5983. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  5984. ne01, ne11, ne10,
  5985. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5986. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5987. ); // NOLINT
  5988. if (x_non_contig || qx_needs_dequant) {
  5989. ctx->prealloc_x_need_sync = true;
  5990. }
  5991. if (y_non_contig || quantize_y) {
  5992. ctx->prealloc_y_need_sync = true;
  5993. }
  5994. }
  5995. // Device tuning
  5996. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5997. if (device->mmvq_mode == 1) {
  5998. return true;
  5999. } else if (device->mmvq_mode == -1) {
  6000. return false;
  6001. }
  6002. // General performance issue with q3_k and q6_k due to 2-byte alignment
  6003. if (src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_Q6_K) {
  6004. return false;
  6005. }
  6006. // MMVQ is generally good for batches
  6007. if (n > 1) {
  6008. return true;
  6009. }
  6010. // Quantization overhead is not worth it for small k
  6011. switch (device->vendor_id) {
  6012. case VK_VENDOR_ID_NVIDIA:
  6013. if (src0_type == GGML_TYPE_Q2_K) {
  6014. return true;
  6015. }
  6016. if (k <= 4096) {
  6017. return false;
  6018. }
  6019. switch (src0_type) {
  6020. case GGML_TYPE_MXFP4:
  6021. case GGML_TYPE_Q8_0:
  6022. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  6023. default:
  6024. return true;
  6025. }
  6026. case VK_VENDOR_ID_AMD:
  6027. if (k < 2048) {
  6028. return false;
  6029. }
  6030. switch (src0_type) {
  6031. case GGML_TYPE_Q8_0:
  6032. return device->architecture == vk_device_architecture::AMD_GCN;
  6033. default:
  6034. return true;
  6035. }
  6036. case VK_VENDOR_ID_INTEL:
  6037. if (k < 2048) {
  6038. return false;
  6039. }
  6040. switch (src0_type) {
  6041. // From tests on A770 Linux, may need more tuning
  6042. case GGML_TYPE_Q4_0:
  6043. case GGML_TYPE_Q5_1:
  6044. return false;
  6045. default:
  6046. return true;
  6047. }
  6048. default:
  6049. return true;
  6050. }
  6051. GGML_UNUSED(m);
  6052. }
  6053. 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) {
  6054. ggml_tensor * dst = cgraph->nodes[node_idx];
  6055. const ggml_tensor * src0 = dst->src[0];
  6056. const ggml_tensor * src1 = dst->src[1];
  6057. 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];
  6058. 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];
  6059. 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];
  6060. std::cerr << ")),)");
  6061. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6062. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6063. const uint64_t ne00 = src0->ne[0];
  6064. const uint64_t ne01 = src0->ne[1];
  6065. const uint64_t ne02 = src0->ne[2];
  6066. const uint64_t ne03 = src0->ne[3];
  6067. const uint64_t ne10 = src1->ne[0];
  6068. const uint64_t ne11 = src1->ne[1];
  6069. const uint64_t ne12 = src1->ne[2];
  6070. const uint64_t ne13 = src1->ne[3];
  6071. const uint64_t ne20 = dst->ne[0];
  6072. const uint64_t ne21 = dst->ne[1];
  6073. // const uint64_t ne22 = dst->ne[2];
  6074. // const uint64_t ne23 = dst->ne[3];
  6075. const uint64_t r2 = ne12 / ne02;
  6076. const uint64_t r3 = ne13 / ne03;
  6077. // batch_n indicates that we need to compute a few vector results, and this assumes
  6078. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  6079. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  6080. bool batch_n = ne11 > 1;
  6081. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6082. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6083. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6084. 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);
  6085. vk_pipeline to_fp16_vk_0 = nullptr;
  6086. vk_pipeline to_fp16_vk_1 = nullptr;
  6087. if (x_non_contig) {
  6088. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6089. }
  6090. if (y_non_contig) {
  6091. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6092. } else {
  6093. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6094. }
  6095. // Check for mmq first
  6096. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  6097. vk_pipeline to_q8_1 = nullptr;
  6098. if (dmmv == nullptr) {
  6099. // Fall back to f16 dequant mul mat
  6100. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  6101. quantize_y = false;
  6102. }
  6103. if (quantize_y) {
  6104. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6105. }
  6106. const bool qx_needs_dequant = x_non_contig;
  6107. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6108. // Not implemented
  6109. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6110. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6111. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6112. GGML_ASSERT(dmmv != nullptr);
  6113. const uint64_t x_ne = ggml_nelements(src0);
  6114. const uint64_t y_ne = ggml_nelements(src1);
  6115. 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);
  6116. 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;
  6117. 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)) :
  6118. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6119. {
  6120. if (
  6121. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6122. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6123. GGML_ABORT("Requested preallocation size is too large");
  6124. }
  6125. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6126. ctx->prealloc_size_x = x_sz;
  6127. ggml_vk_preallocate_buffers(ctx, subctx);
  6128. }
  6129. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6130. ctx->prealloc_size_y = y_sz;
  6131. ggml_vk_preallocate_buffers(ctx, subctx);
  6132. }
  6133. // Request descriptor sets
  6134. if (qx_needs_dequant) {
  6135. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6136. }
  6137. if (qy_needs_dequant) {
  6138. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6139. }
  6140. if (quantize_y) {
  6141. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6142. }
  6143. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6144. }
  6145. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6146. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6147. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6148. vk_subbuffer d_X, d_Y;
  6149. if (qx_needs_dequant) {
  6150. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6151. } else {
  6152. d_X = d_Qx;
  6153. GGML_ASSERT(qx_sz == x_sz);
  6154. }
  6155. if (qy_needs_dequant || quantize_y) {
  6156. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6157. } else {
  6158. d_Y = d_Qy;
  6159. }
  6160. if (x_non_contig) {
  6161. if (ctx->prealloc_x_need_sync) {
  6162. ggml_vk_sync_buffers(ctx, subctx);
  6163. }
  6164. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6165. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6166. }
  6167. if (y_non_contig) {
  6168. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6169. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6170. ctx->prealloc_y_last_tensor_used != src1) {
  6171. if (ctx->prealloc_y_need_sync) {
  6172. ggml_vk_sync_buffers(ctx, subctx);
  6173. }
  6174. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6175. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6176. ctx->prealloc_y_last_tensor_used = src1;
  6177. }
  6178. }
  6179. if (quantize_y) {
  6180. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6181. ctx->prealloc_y_last_tensor_used != src1) {
  6182. if (ctx->prealloc_y_need_sync) {
  6183. ggml_vk_sync_buffers(ctx, subctx);
  6184. }
  6185. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6186. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6187. ctx->prealloc_y_last_tensor_used = src1;
  6188. }
  6189. }
  6190. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  6191. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  6192. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  6193. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  6194. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6195. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6196. }
  6197. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6198. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6199. }
  6200. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6201. uint32_t groups_x = ne01;
  6202. uint32_t groups_z = 1;
  6203. if (ne01 > max_groups_x) {
  6204. groups_z = 64;
  6205. groups_x = CEIL_DIV(groups_x, groups_z);
  6206. }
  6207. uint32_t fusion_flags = 0;
  6208. vk_subbuffer d_F0 = d_D;
  6209. if (ctx->num_additional_fused_ops > 0) {
  6210. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6211. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6212. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6213. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6214. }
  6215. vk_subbuffer d_F1 = d_D;
  6216. if (ctx->num_additional_fused_ops == 2) {
  6217. const ggml_tensor * add = cgraph->nodes[node_idx + 2];
  6218. const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0];
  6219. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6220. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6221. }
  6222. // compute
  6223. const vk_mat_vec_push_constants pc = {
  6224. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6225. stride_batch_x, stride_batch_y, stride_batch_d,
  6226. fusion_flags,
  6227. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  6228. };
  6229. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6230. {
  6231. d_X,
  6232. d_Y,
  6233. d_D,
  6234. d_F0,
  6235. d_F1,
  6236. },
  6237. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  6238. if (x_non_contig) {
  6239. ctx->prealloc_x_need_sync = true;
  6240. }
  6241. if (y_non_contig || quantize_y) {
  6242. ctx->prealloc_y_need_sync = true;
  6243. }
  6244. }
  6245. 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) {
  6246. ggml_tensor * dst = cgraph->nodes[node_idx];
  6247. const ggml_tensor * src0 = dst->src[0];
  6248. const ggml_tensor * src1 = dst->src[1];
  6249. 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];
  6250. 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];
  6251. 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];
  6252. std::cerr << "))");
  6253. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  6254. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  6255. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  6256. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6257. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6258. const uint64_t ne00 = src0->ne[0];
  6259. const uint64_t ne01 = src0->ne[1];
  6260. const uint64_t ne02 = src0->ne[2];
  6261. // const uint64_t ne03 = src0->ne[3];
  6262. //const uint64_t ne10 = src1->ne[0];
  6263. const uint64_t ne11 = src1->ne[1];
  6264. const uint64_t ne12 = src1->ne[2];
  6265. // const uint64_t ne13 = src1->ne[3];
  6266. GGML_ASSERT(ne11 == 1);
  6267. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  6268. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  6269. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  6270. gqa_ratio = 1;
  6271. }
  6272. {
  6273. // Request descriptor sets
  6274. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  6275. }
  6276. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6277. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6278. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6279. vk_subbuffer d_F0 = d_D;
  6280. uint32_t fusion_flags = 0;
  6281. if (ctx->num_additional_fused_ops > 0) {
  6282. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6283. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6284. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6285. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6286. }
  6287. vk_subbuffer d_F1 = d_D;
  6288. if (ctx->num_additional_fused_ops > 1) {
  6289. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6290. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6291. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6292. }
  6293. // compute
  6294. vk_mat_vec_p021_push_constants pc = {
  6295. (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12,
  6296. 0, 0, fusion_flags
  6297. };
  6298. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6299. uint32_t workgroups_z = (uint32_t)ne12;
  6300. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  6301. if (gqa_ratio > 1) {
  6302. workgroups_z /= gqa_ratio;
  6303. }
  6304. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6305. {
  6306. d_Qx,
  6307. d_Qy,
  6308. d_D,
  6309. d_F0,
  6310. d_F1,
  6311. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6312. }
  6313. 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) {
  6314. ggml_tensor * dst = cgraph->nodes[node_idx];
  6315. const ggml_tensor * src0 = dst->src[0];
  6316. const ggml_tensor * src1 = dst->src[1];
  6317. 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];
  6318. 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];
  6319. 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];
  6320. std::cerr << "))");
  6321. GGML_ASSERT(!ggml_is_transposed(src0));
  6322. GGML_ASSERT(!ggml_is_transposed(src1));
  6323. GGML_ASSERT(!ggml_is_permuted(src0));
  6324. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6325. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6326. const uint64_t ne00 = src0->ne[0];
  6327. const uint64_t ne01 = src0->ne[1];
  6328. const uint64_t ne02 = src0->ne[2];
  6329. const uint64_t ne03 = src0->ne[3];
  6330. const uint64_t nb01 = src0->nb[1];
  6331. const uint64_t nb02 = src0->nb[2];
  6332. const uint64_t nb12 = src1->nb[2];
  6333. // const uint64_t ne10 = src1->ne[0];
  6334. const uint64_t ne11 = src1->ne[1];
  6335. const uint64_t ne12 = src1->ne[2];
  6336. // const uint64_t ne13 = src1->ne[3];
  6337. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6338. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6339. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6340. GGML_ASSERT(ne11 == 1);
  6341. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6342. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6343. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6344. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6345. {
  6346. // Request descriptor sets
  6347. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6348. }
  6349. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6350. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6351. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6352. vk_subbuffer d_F0 = d_D;
  6353. uint32_t fusion_flags = 0;
  6354. if (ctx->num_additional_fused_ops > 0) {
  6355. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6356. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6357. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6358. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6359. }
  6360. vk_subbuffer d_F1 = d_D;
  6361. if (ctx->num_additional_fused_ops > 1) {
  6362. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6363. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6364. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6365. }
  6366. // compute
  6367. vk_mat_vec_nc_push_constants pc = {
  6368. (uint32_t)ne00, (uint32_t)ne01,
  6369. row_stride_x, channel_stride_x, channel_stride_y,
  6370. (uint32_t)(ne12 / ne02), (uint32_t)ne12,
  6371. 0, 0,
  6372. nb03, nb13, nb23, fusion_flags
  6373. };
  6374. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6375. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6376. {
  6377. d_Qx,
  6378. d_Qy,
  6379. d_D,
  6380. d_F0,
  6381. d_F1,
  6382. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6383. }
  6384. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6385. ggml_tensor * dst = cgraph->nodes[node_idx];
  6386. ggml_tensor * src0 = dst->src[0];
  6387. ggml_tensor * src1 = dst->src[1];
  6388. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6389. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6390. // where the M dimension is very large.
  6391. // Split_k doesn't work with M splitting.
  6392. const size_t nbytes = ggml_nbytes(src0);
  6393. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6394. if (needs_split) {
  6395. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6396. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6397. uint32_t m_offset = 0;
  6398. while (m_offset < dst->ne[0]) {
  6399. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6400. ggml_tensor dst2 = *dst;
  6401. ggml_tensor src02 = *src0;
  6402. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6403. src02.view_src = src0->view_src ? src0->view_src : src0;
  6404. dst2.view_offs += m_offset * dst->nb[0];
  6405. src02.view_offs += m_offset * src0->nb[1];
  6406. dst2.ne[0] = cur_M_size;
  6407. src02.ne[1] = cur_M_size;
  6408. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6409. m_offset += cur_M_size;
  6410. }
  6411. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6412. // detect 0213 permutation, and batch size of 1
  6413. src0->nb[0] <= src0->nb[2] &&
  6414. src0->nb[2] <= src0->nb[1] &&
  6415. src0->nb[1] <= src0->nb[3] &&
  6416. src1->nb[0] <= src1->nb[2] &&
  6417. src1->nb[2] <= src1->nb[1] &&
  6418. src1->nb[1] <= src1->nb[3] &&
  6419. src0->ne[3] == 1 &&
  6420. src1->ne[3] == 1) {
  6421. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6422. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6423. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6424. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6425. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6426. // when ne12 and ne13 are one.
  6427. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6428. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6429. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6430. } else {
  6431. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6432. }
  6433. }
  6434. 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) {
  6435. 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];
  6436. 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];
  6437. 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];
  6438. 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] << "),)");
  6439. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6440. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6441. const uint64_t ne00 = src0->ne[0];
  6442. const uint64_t ne01 = src0->ne[1];
  6443. const uint64_t ne02 = src0->ne[2];
  6444. // const uint64_t ne03 = src0->ne[3];
  6445. const uint64_t ne10 = src1->ne[0];
  6446. const uint64_t ne11 = src1->ne[1];
  6447. const uint64_t ne12 = src1->ne[2];
  6448. const uint64_t ne13 = src1->ne[3];
  6449. const uint64_t nei0 = ids->ne[0];
  6450. const uint64_t nei1 = ids->ne[1];
  6451. const uint32_t nbi1 = ids->nb[1];
  6452. const uint32_t nbi2 = ids->nb[2];
  6453. const uint64_t ne20 = dst->ne[0];
  6454. const uint64_t ne21 = dst->ne[1];
  6455. // const uint64_t ne22 = dst->ne[2];
  6456. // const uint64_t ne23 = dst->ne[3];
  6457. const uint64_t n_as = ne02;
  6458. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6459. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6460. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6461. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6462. vk_buffer d_Qx = nullptr;
  6463. size_t qx_buf_offset = 0;
  6464. vk_buffer d_Qy = nullptr;
  6465. size_t qy_buf_offset = 0;
  6466. vk_buffer d_ids = nullptr;
  6467. size_t ids_buf_offset = 0;
  6468. bool src0_uma = false;
  6469. bool src1_uma = false;
  6470. bool ids_uma = false;
  6471. if (ctx->device->uma) {
  6472. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6473. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6474. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6475. src0_uma = d_Qx != nullptr;
  6476. src1_uma = d_Qy != nullptr;
  6477. ids_uma = d_ids != nullptr;
  6478. }
  6479. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6480. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6481. !ggml_vk_dim01_contiguous(src0);
  6482. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6483. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6484. !ggml_vk_dim01_contiguous(src1);
  6485. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6486. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6487. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6488. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6489. // Check for mmq first
  6490. 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;
  6491. if (mmp == nullptr) {
  6492. // Fall back to f16 dequant mul mat
  6493. 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]);
  6494. quantize_y = false;
  6495. }
  6496. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6497. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6498. if (qx_needs_dequant) {
  6499. // Fall back to dequant + f16 mulmat
  6500. 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]);
  6501. }
  6502. // Not implemented
  6503. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6504. 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));
  6505. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6506. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6507. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6508. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6509. const uint64_t x_ne = ggml_nelements(src0);
  6510. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6511. const uint64_t d_ne = ggml_nelements(dst);
  6512. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6513. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6514. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6515. 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);
  6516. const uint64_t ids_sz = nbi2;
  6517. const uint64_t d_sz = sizeof(float) * d_ne;
  6518. vk_pipeline to_fp16_vk_0 = nullptr;
  6519. vk_pipeline to_fp16_vk_1 = nullptr;
  6520. vk_pipeline to_q8_1 = nullptr;
  6521. if (x_non_contig) {
  6522. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6523. } else {
  6524. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6525. }
  6526. if (y_non_contig) {
  6527. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6528. } else {
  6529. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6530. }
  6531. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6532. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6533. if (quantize_y) {
  6534. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6535. }
  6536. {
  6537. if (
  6538. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6539. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6540. GGML_ABORT("Requested preallocation size is too large");
  6541. }
  6542. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6543. ctx->prealloc_size_x = x_sz;
  6544. ggml_vk_preallocate_buffers(ctx, subctx);
  6545. }
  6546. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6547. ctx->prealloc_size_y = y_sz;
  6548. ggml_vk_preallocate_buffers(ctx, subctx);
  6549. }
  6550. // Request descriptor sets
  6551. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6552. if (qx_needs_dequant) {
  6553. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6554. }
  6555. if (qy_needs_dequant) {
  6556. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6557. }
  6558. if (quantize_y) {
  6559. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6560. }
  6561. }
  6562. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6563. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6564. GGML_ASSERT(d_D != nullptr);
  6565. vk_buffer d_X;
  6566. uint64_t x_buf_offset = 0;
  6567. vk_buffer d_Y;
  6568. uint64_t y_buf_offset = 0;
  6569. if (!src0_uma) {
  6570. d_Qx = src0_buf_ctx->dev_buffer;
  6571. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6572. GGML_ASSERT(d_Qx != nullptr);
  6573. }
  6574. if (!src1_uma) {
  6575. d_Qy = src1_buf_ctx->dev_buffer;
  6576. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6577. GGML_ASSERT(d_Qy != nullptr);
  6578. }
  6579. if (!ids_uma) {
  6580. d_ids = ids_buf_ctx->dev_buffer;
  6581. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6582. GGML_ASSERT(d_ids != nullptr);
  6583. }
  6584. if (qx_needs_dequant) {
  6585. d_X = ctx->prealloc_x;
  6586. GGML_ASSERT(d_X->size >= x_sz);
  6587. } else {
  6588. d_X = d_Qx;
  6589. x_buf_offset = qx_buf_offset;
  6590. GGML_ASSERT(qx_sz == x_sz);
  6591. }
  6592. if (qy_needs_dequant) {
  6593. d_Y = ctx->prealloc_y;
  6594. GGML_ASSERT(d_Y->size >= y_sz);
  6595. } else if (quantize_y) {
  6596. d_Y = ctx->prealloc_y;
  6597. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6598. } else {
  6599. d_Y = d_Qy;
  6600. y_buf_offset = qy_buf_offset;
  6601. GGML_ASSERT(qy_sz == y_sz);
  6602. }
  6603. if (x_non_contig || qx_needs_dequant) {
  6604. if (ctx->prealloc_x_need_sync) {
  6605. ggml_vk_sync_buffers(ctx, subctx);
  6606. }
  6607. }
  6608. if (x_non_contig) {
  6609. 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));
  6610. } else if (qx_needs_dequant) {
  6611. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6612. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6613. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6614. ggml_vk_sync_buffers(ctx, subctx);
  6615. }
  6616. if (y_non_contig) {
  6617. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6618. ctx->prealloc_y_last_tensor_used != src1) {
  6619. if (ctx->prealloc_y_need_sync) {
  6620. ggml_vk_sync_buffers(ctx, subctx);
  6621. }
  6622. 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));
  6623. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6624. ctx->prealloc_y_last_tensor_used = src1;
  6625. }
  6626. }
  6627. if (quantize_y) {
  6628. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6629. ctx->prealloc_y_last_tensor_used != src1) {
  6630. if (ctx->prealloc_y_need_sync) {
  6631. ggml_vk_sync_buffers(ctx, subctx);
  6632. }
  6633. 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);
  6634. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6635. ctx->prealloc_y_last_tensor_used = src1;
  6636. }
  6637. }
  6638. uint32_t stride_batch_x = ne00*ne01;
  6639. uint32_t stride_batch_y = ne10*ne11;
  6640. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6641. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6642. }
  6643. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6644. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6645. }
  6646. // compute
  6647. ggml_vk_matmul_id(
  6648. ctx, subctx, pipeline,
  6649. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6650. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz },
  6651. ne01, ne21, ne10, ne10, ne10, ne01,
  6652. stride_batch_x, stride_batch_y, ne20*ne21,
  6653. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6654. ); // NOLINT
  6655. if (x_non_contig || qx_needs_dequant) {
  6656. ctx->prealloc_x_need_sync = true;
  6657. }
  6658. if (y_non_contig || quantize_y) {
  6659. ctx->prealloc_y_need_sync = true;
  6660. }
  6661. }
  6662. 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) {
  6663. ggml_tensor * dst = cgraph->nodes[node_idx];
  6664. ggml_tensor * src0 = dst->src[0];
  6665. ggml_tensor * src1 = dst->src[1];
  6666. ggml_tensor * ids = dst->src[2];
  6667. 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];
  6668. 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];
  6669. 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];
  6670. 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];
  6671. std::cerr << "))");
  6672. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6673. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6674. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6675. const uint64_t ne00 = src0->ne[0];
  6676. const uint64_t ne01 = src0->ne[1];
  6677. // const uint64_t ne02 = src0->ne[2];
  6678. // const uint64_t ne03 = src0->ne[3];
  6679. const uint64_t ne10 = src1->ne[0];
  6680. const uint64_t ne11 = src1->ne[1];
  6681. const uint64_t ne12 = src1->ne[2];
  6682. // const uint64_t ne13 = src1->ne[3];
  6683. const uint64_t nei0 = ids->ne[0];
  6684. const uint64_t nei1 = ids->ne[1];
  6685. GGML_ASSERT(nei1 == 1);
  6686. const uint64_t ne20 = dst->ne[0];
  6687. const uint64_t ne21 = dst->ne[1];
  6688. // const uint64_t ne22 = dst->ne[2];
  6689. // const uint64_t ne23 = dst->ne[3];
  6690. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6691. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6692. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6693. 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);
  6694. vk_pipeline to_fp16_vk_0 = nullptr;
  6695. vk_pipeline to_fp16_vk_1 = nullptr;
  6696. if (x_non_contig) {
  6697. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6698. }
  6699. if (y_non_contig) {
  6700. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6701. } else {
  6702. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6703. }
  6704. // Check for mmq first
  6705. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00) : nullptr;
  6706. vk_pipeline to_q8_1 = nullptr;
  6707. if (dmmv == nullptr) {
  6708. // Fall back to f16 dequant mul mat
  6709. dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00);
  6710. quantize_y = false;
  6711. }
  6712. if (quantize_y) {
  6713. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6714. }
  6715. const bool qx_needs_dequant = x_non_contig;
  6716. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6717. // Not implemented
  6718. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6719. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6720. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6721. GGML_ASSERT(dmmv != nullptr);
  6722. const uint64_t x_ne = ggml_nelements(src0);
  6723. const uint64_t y_ne = ggml_nelements(src1);
  6724. 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);
  6725. 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;
  6726. 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)) :
  6727. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6728. {
  6729. if (
  6730. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6731. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6732. GGML_ABORT("Requested preallocation size is too large");
  6733. }
  6734. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6735. ctx->prealloc_size_x = x_sz;
  6736. ggml_vk_preallocate_buffers(ctx, subctx);
  6737. }
  6738. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6739. ctx->prealloc_size_y = y_sz;
  6740. ggml_vk_preallocate_buffers(ctx, subctx);
  6741. }
  6742. // Request descriptor sets
  6743. if (qx_needs_dequant) {
  6744. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6745. }
  6746. if (qy_needs_dequant) {
  6747. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6748. }
  6749. if (quantize_y) {
  6750. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6751. }
  6752. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6753. }
  6754. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6755. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6756. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6757. vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids);
  6758. vk_subbuffer d_F0 = d_D;
  6759. vk_subbuffer d_X, d_Y;
  6760. if (qx_needs_dequant) {
  6761. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6762. } else {
  6763. d_X = d_Qx;
  6764. }
  6765. if (qy_needs_dequant || quantize_y) {
  6766. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6767. } else {
  6768. d_Y = d_Qy;
  6769. }
  6770. if (x_non_contig) {
  6771. if (ctx->prealloc_x_need_sync) {
  6772. ggml_vk_sync_buffers(ctx, subctx);
  6773. }
  6774. }
  6775. if (x_non_contig) {
  6776. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6777. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6778. }
  6779. if (y_non_contig) {
  6780. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6781. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6782. ctx->prealloc_y_last_tensor_used != src1) {
  6783. if (ctx->prealloc_y_need_sync) {
  6784. ggml_vk_sync_buffers(ctx, subctx);
  6785. }
  6786. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6787. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6788. ctx->prealloc_y_last_tensor_used = src1;
  6789. }
  6790. }
  6791. if (quantize_y) {
  6792. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6793. ctx->prealloc_y_last_tensor_used != src1) {
  6794. if (ctx->prealloc_y_need_sync) {
  6795. ggml_vk_sync_buffers(ctx, subctx);
  6796. }
  6797. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6798. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6799. ctx->prealloc_y_last_tensor_used = src1;
  6800. }
  6801. }
  6802. uint32_t stride_batch_y = ne10*ne11;
  6803. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6804. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6805. }
  6806. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6807. uint32_t groups_x = ne01;
  6808. uint32_t groups_z = 1;
  6809. if (ne01 > max_groups_x) {
  6810. groups_z = 64;
  6811. groups_x = CEIL_DIV(groups_x, groups_z);
  6812. }
  6813. uint32_t fusion_flags = 0;
  6814. if (ctx->num_additional_fused_ops > 0) {
  6815. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6816. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6817. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  6818. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0;
  6819. } else {
  6820. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  6821. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6822. }
  6823. }
  6824. vk_subbuffer d_F1 = d_D;
  6825. if (ctx->num_additional_fused_ops > 1) {
  6826. const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1];
  6827. d_F1 = ggml_vk_tensor_subbuffer(ctx, scale);
  6828. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
  6829. }
  6830. // compute
  6831. const vk_mat_vec_id_push_constants pc = {
  6832. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6833. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  6834. fusion_flags,
  6835. (uint32_t)nei0, (uint32_t)ne11,
  6836. };
  6837. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6838. {
  6839. d_X,
  6840. d_Y,
  6841. d_D,
  6842. d_F0,
  6843. d_F1,
  6844. d_ids,
  6845. },
  6846. pc, { groups_x, (uint32_t)nei0, groups_z });
  6847. if (x_non_contig) {
  6848. ctx->prealloc_x_need_sync = true;
  6849. }
  6850. if (y_non_contig || quantize_y) {
  6851. ctx->prealloc_y_need_sync = true;
  6852. }
  6853. }
  6854. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  6855. ggml_tensor * dst = cgraph->nodes[node_idx];
  6856. ggml_tensor * src0 = dst->src[0];
  6857. ggml_tensor * src2 = dst->src[2];
  6858. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  6859. }
  6860. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6861. ggml_tensor * dst = cgraph->nodes[node_idx];
  6862. ggml_tensor * src0 = dst->src[0];
  6863. ggml_tensor * src1 = dst->src[1];
  6864. ggml_tensor * src2 = dst->src[2];
  6865. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6866. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  6867. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  6868. } else {
  6869. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  6870. }
  6871. }
  6872. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool small_cache) {
  6873. // Needs to be kept up to date on shader changes
  6874. GGML_UNUSED(hsv);
  6875. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6876. const uint32_t Br = get_fa_scalar_num_large_rows(hsk, hsv, small_cache);
  6877. const uint32_t Bc = scalar_flash_attention_Bc;
  6878. const uint32_t tmpsh = wg_size * sizeof(float);
  6879. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6880. const uint32_t masksh = Bc * Br * sizeof(float);
  6881. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6882. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6883. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6884. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6885. return supported;
  6886. }
  6887. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6888. // Needs to be kept up to date on shader changes
  6889. GGML_UNUSED(hsv);
  6890. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6891. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6892. const uint32_t Bc = scalar_flash_attention_Bc;
  6893. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6894. const uint32_t acctype = f32acc ? 4 : 2;
  6895. const uint32_t f16vec4 = 8;
  6896. const uint32_t tmpsh = wg_size * sizeof(float);
  6897. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6898. const uint32_t qstride = hsk_pad / 4 + 2;
  6899. const uint32_t Qf = Br * qstride * f16vec4;
  6900. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6901. const uint32_t sfsh = Bc * sfshstride * acctype;
  6902. const uint32_t kshstride = hsk_pad / 4 + 2;
  6903. const uint32_t ksh = Bc * kshstride * f16vec4;
  6904. const uint32_t slope = Br * sizeof(float);
  6905. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6906. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6907. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6908. return supported;
  6909. }
  6910. 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) {
  6911. 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];
  6912. 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];
  6913. 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];
  6914. 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];
  6915. if (sinks) {
  6916. 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];
  6917. }
  6918. std::cerr << "))");
  6919. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6920. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6921. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6922. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6923. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6924. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6925. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6926. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6927. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6928. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6929. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6930. const uint32_t HSK = nek0;
  6931. const uint32_t HSV = nev0;
  6932. uint32_t N = neq1;
  6933. const uint32_t KV = nek1;
  6934. GGML_ASSERT(ne0 == HSV);
  6935. GGML_ASSERT(ne2 == N);
  6936. // input tensor rows must be contiguous
  6937. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6938. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6939. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6940. GGML_ASSERT(neq0 == HSK);
  6941. GGML_ASSERT(neq1 == N);
  6942. GGML_ASSERT(nev1 == nek1);
  6943. // dst cannot be transposed or permuted
  6944. GGML_ASSERT(nb0 == sizeof(float));
  6945. GGML_ASSERT(nb0 <= nb1);
  6946. GGML_ASSERT(nb1 <= nb2);
  6947. GGML_ASSERT(nb2 <= nb3);
  6948. assert(dst->type == GGML_TYPE_F32);
  6949. assert(q->type == GGML_TYPE_F32);
  6950. assert(k->type == v->type);
  6951. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6952. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6953. if (path == FA_COOPMAT1) {
  6954. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6955. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6956. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6957. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6958. path = FA_SCALAR;
  6959. }
  6960. }
  6961. uint32_t gqa_ratio = 1;
  6962. uint32_t qk_ratio = neq2 / nek2;
  6963. uint32_t workgroups_x = (uint32_t)neq1;
  6964. uint32_t workgroups_y = (uint32_t)neq2;
  6965. uint32_t workgroups_z = (uint32_t)neq3;
  6966. const bool small_cache = nek1 < 1024;
  6967. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6968. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6969. uint32_t max_gqa;
  6970. switch (path) {
  6971. case FA_SCALAR:
  6972. case FA_COOPMAT1:
  6973. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6974. max_gqa = get_fa_scalar_num_large_rows(HSK, HSV, small_cache);
  6975. break;
  6976. case FA_COOPMAT2:
  6977. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6978. break;
  6979. default:
  6980. GGML_ASSERT(0);
  6981. }
  6982. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6983. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6984. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6985. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6986. // and change addressing calculations to index Q's dimension 2.
  6987. gqa_ratio = qk_ratio;
  6988. N = gqa_ratio;
  6989. workgroups_y /= N;
  6990. }
  6991. bool small_rows = N <= get_fa_num_small_rows(path);
  6992. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6993. // So use scalar instead.
  6994. if (small_rows && path == FA_COOPMAT1) {
  6995. path = FA_SCALAR;
  6996. }
  6997. // scalar is faster than coopmat2 when N==1
  6998. if (N == 1 && path == FA_COOPMAT2) {
  6999. path = FA_SCALAR;
  7000. }
  7001. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  7002. if (path == FA_SCALAR &&
  7003. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV, small_cache)) {
  7004. small_rows = true;
  7005. }
  7006. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  7007. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  7008. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  7009. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  7010. if (k->type == GGML_TYPE_F32) {
  7011. k_stride /= 4;
  7012. }
  7013. if (v->type == GGML_TYPE_F32) {
  7014. v_stride /= 4;
  7015. }
  7016. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows, small_cache);
  7017. bool aligned = (KV % alignment) == 0 &&
  7018. // the "aligned" shader variant will forcibly align strides, for performance
  7019. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  7020. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  7021. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  7022. aligned = false;
  7023. }
  7024. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  7025. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, small_cache, path, aligned, f32acc);
  7026. vk_pipeline pipeline = nullptr;
  7027. {
  7028. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7029. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  7030. auto it = pipelines.find(fa_pipeline_state);
  7031. if (it != pipelines.end()) {
  7032. pipeline = it->second;
  7033. } else {
  7034. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7035. }
  7036. }
  7037. assert(pipeline);
  7038. uint32_t split_kv = KV;
  7039. uint32_t split_k = 1;
  7040. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  7041. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  7042. // Try to use split_k when KV is large enough to be worth the overhead
  7043. if (workgroups_x == 1 && shader_core_count > 0) {
  7044. // Try to run two workgroups per SM.
  7045. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  7046. if (split_k > 1) {
  7047. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  7048. // of "align", so recompute split_k based on that.
  7049. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  7050. split_k = CEIL_DIV(KV, split_kv);
  7051. workgroups_x = split_k;
  7052. }
  7053. }
  7054. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  7055. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  7056. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  7057. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  7058. GGML_ABORT("Requested preallocation size is too large");
  7059. }
  7060. if (ctx->prealloc_size_split_k < split_k_size) {
  7061. ctx->prealloc_size_split_k = split_k_size;
  7062. ggml_vk_preallocate_buffers(ctx, subctx);
  7063. }
  7064. {
  7065. // Request descriptor sets
  7066. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7067. if (split_k > 1) {
  7068. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  7069. }
  7070. }
  7071. float scale = 1.0f;
  7072. float max_bias = 0.0f;
  7073. float logit_softcap = 0.0f;
  7074. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  7075. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  7076. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  7077. if (logit_softcap != 0) {
  7078. scale /= logit_softcap;
  7079. }
  7080. const uint32_t n_head_kv = neq2;
  7081. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  7082. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  7083. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  7084. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  7085. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  7086. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  7087. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  7088. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  7089. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  7090. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  7091. const vk_flash_attn_push_constants pc = { N, KV,
  7092. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  7093. (uint32_t)neq2, (uint32_t)neq3,
  7094. (uint32_t)nek2, (uint32_t)nek3,
  7095. (uint32_t)nev2, (uint32_t)nev3,
  7096. nem1, nem2, nem3,
  7097. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  7098. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  7099. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  7100. scale, max_bias, logit_softcap,
  7101. mask_n_head_log2, m0, m1,
  7102. gqa_ratio, split_kv, split_k };
  7103. if (split_k > 1) {
  7104. if (ctx->prealloc_split_k_need_sync) {
  7105. ggml_vk_sync_buffers(ctx, subctx);
  7106. }
  7107. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  7108. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7109. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  7110. // We only use split_k when group query attention is enabled, which means
  7111. // there's no more than one tile of rows (i.e. workgroups_x would have been
  7112. // one). We reuse workgroups_x to mean the number of splits, so we need to
  7113. // cancel out the divide by wg_denoms[0].
  7114. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  7115. ggml_vk_sync_buffers(ctx, subctx);
  7116. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  7117. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  7118. {split_k_buf, sinks_buf, dst_buf},
  7119. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  7120. ctx->prealloc_split_k_need_sync = true;
  7121. } else {
  7122. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7123. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  7124. pc, { workgroups_x, workgroups_y, workgroups_z });
  7125. }
  7126. }
  7127. static vk_conv_shapes ggml_vk_conv_select_shape(ggml_backend_vk_context * ctx, uint32_t K, uint32_t NPQ) {
  7128. auto n_tiles = [&](vk_conv_shapes s) {
  7129. return CEIL_DIV(K, vk_conv_block_sizes[s].K)
  7130. * CEIL_DIV(NPQ, vk_conv_block_sizes[s].NPQ);
  7131. };
  7132. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7133. // so small convolutions will still choose a smaller tile.
  7134. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7135. if (K > 64 && n_tiles(CONV_SHAPE_128x128) >= shader_core_count * 2) {
  7136. return CONV_SHAPE_128x128;
  7137. } else if (K <= 32 && n_tiles(CONV_SHAPE_32x256) >= shader_core_count * 2) {
  7138. return CONV_SHAPE_32x256;
  7139. } else {
  7140. return CONV_SHAPE_64x32;
  7141. }
  7142. }
  7143. 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) {
  7144. switch (op) {
  7145. case GGML_OP_GET_ROWS:
  7146. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  7147. if (src0->type == GGML_TYPE_I32) {
  7148. // i32 src only supports i32 result
  7149. GGML_ASSERT(dst->type == GGML_TYPE_I32);
  7150. return ctx->device->pipeline_get_rows[src0->type];
  7151. }
  7152. if (dst->type == GGML_TYPE_F16) {
  7153. return ctx->device->pipeline_get_rows[src0->type];
  7154. }
  7155. if (dst->type == GGML_TYPE_F32) {
  7156. return ctx->device->pipeline_get_rows_f32[src0->type];
  7157. }
  7158. return nullptr;
  7159. case GGML_OP_ACC:
  7160. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7161. return ctx->device->pipeline_acc_f32;
  7162. }
  7163. return nullptr;
  7164. case GGML_OP_ADD:
  7165. case GGML_OP_SUB:
  7166. case GGML_OP_MUL:
  7167. case GGML_OP_DIV:
  7168. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7169. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  7170. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  7171. return nullptr;
  7172. }
  7173. switch (op) {
  7174. case GGML_OP_ADD:
  7175. {
  7176. if (ctx->num_additional_fused_ops > 0) {
  7177. if (ctx->do_add_rms_partials) {
  7178. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  7179. } else {
  7180. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  7181. }
  7182. }
  7183. if (ctx->do_add_rms_partials) {
  7184. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  7185. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7186. } else {
  7187. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  7188. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7189. }
  7190. }
  7191. case GGML_OP_SUB:
  7192. {
  7193. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  7194. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7195. }
  7196. case GGML_OP_MUL:
  7197. {
  7198. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  7199. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7200. }
  7201. case GGML_OP_DIV:
  7202. {
  7203. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  7204. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7205. }
  7206. default:
  7207. break;
  7208. }
  7209. return nullptr;
  7210. case GGML_OP_ADD_ID:
  7211. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7212. return ctx->device->pipeline_add_id_f32;
  7213. }
  7214. return nullptr;
  7215. case GGML_OP_CONCAT:
  7216. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7217. return ctx->device->pipeline_concat_f32;
  7218. }
  7219. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7220. return ctx->device->pipeline_concat_f16;
  7221. }
  7222. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7223. return ctx->device->pipeline_concat_i32;
  7224. }
  7225. return nullptr;
  7226. case GGML_OP_UPSCALE:
  7227. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7228. uint32_t mode = (ggml_get_op_params_i32(dst, 0) & (0xFF | GGML_SCALE_FLAG_ANTIALIAS));
  7229. switch (mode) {
  7230. case GGML_SCALE_MODE_NEAREST:
  7231. return ctx->device->pipeline_upscale_nearest_f32;
  7232. case GGML_SCALE_MODE_BILINEAR:
  7233. return ctx->device->pipeline_upscale_bilinear_f32;
  7234. case GGML_SCALE_MODE_BICUBIC:
  7235. return ctx->device->pipeline_upscale_bicubic_f32;
  7236. case GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS:
  7237. return ctx->device->pipeline_upscale_bilinear_antialias_f32;
  7238. default:
  7239. return nullptr;
  7240. }
  7241. }
  7242. return nullptr;
  7243. case GGML_OP_SCALE:
  7244. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7245. return ctx->device->pipeline_scale_f32;
  7246. }
  7247. return nullptr;
  7248. case GGML_OP_SQR:
  7249. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7250. return ctx->device->pipeline_sqr_f32;
  7251. }
  7252. return nullptr;
  7253. case GGML_OP_SQRT:
  7254. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7255. return ctx->device->pipeline_sqrt_f32;
  7256. }
  7257. return nullptr;
  7258. case GGML_OP_SIN:
  7259. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7260. return ctx->device->pipeline_sin_f32;
  7261. }
  7262. return nullptr;
  7263. case GGML_OP_COS:
  7264. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7265. return ctx->device->pipeline_cos_f32;
  7266. }
  7267. return nullptr;
  7268. case GGML_OP_LOG:
  7269. if (src0->type == dst->type &&
  7270. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7271. return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16];
  7272. }
  7273. return nullptr;
  7274. case GGML_OP_TRI:
  7275. if (src0->type == dst->type &&
  7276. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7277. return ctx->device->pipeline_tri[dst->type == GGML_TYPE_F16];
  7278. }
  7279. return nullptr;
  7280. case GGML_OP_DIAG:
  7281. if (src0->type == dst->type &&
  7282. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7283. return ctx->device->pipeline_diag[dst->type == GGML_TYPE_F16];
  7284. }
  7285. return nullptr;
  7286. case GGML_OP_CLAMP:
  7287. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7288. return ctx->device->pipeline_clamp_f32;
  7289. }
  7290. return nullptr;
  7291. case GGML_OP_PAD:
  7292. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7293. return ctx->device->pipeline_pad_f32;
  7294. }
  7295. return nullptr;
  7296. case GGML_OP_ROLL:
  7297. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7298. return ctx->device->pipeline_roll_f32;
  7299. }
  7300. return nullptr;
  7301. case GGML_OP_REPEAT:
  7302. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7303. return ctx->device->pipeline_repeat_f32;
  7304. }
  7305. return nullptr;
  7306. case GGML_OP_REPEAT_BACK:
  7307. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7308. return ctx->device->pipeline_repeat_back_f32;
  7309. }
  7310. return nullptr;
  7311. case GGML_OP_CPY:
  7312. case GGML_OP_CONT:
  7313. case GGML_OP_DUP:
  7314. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7315. case GGML_OP_SET_ROWS:
  7316. if (src1->type == GGML_TYPE_I64) {
  7317. return ctx->device->pipeline_set_rows_i64[dst->type];
  7318. } else {
  7319. return ctx->device->pipeline_set_rows_i32[dst->type];
  7320. }
  7321. case GGML_OP_SILU_BACK:
  7322. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7323. return ctx->device->pipeline_silu_back_f32;
  7324. }
  7325. return nullptr;
  7326. case GGML_OP_NORM:
  7327. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7328. return ctx->device->pipeline_norm_f32;
  7329. }
  7330. return nullptr;
  7331. case GGML_OP_GROUP_NORM:
  7332. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7333. return ctx->device->pipeline_group_norm_f32;
  7334. }
  7335. return nullptr;
  7336. case GGML_OP_RMS_NORM:
  7337. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7338. if (ctx->do_add_rms_partials) {
  7339. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7340. } else {
  7341. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7342. }
  7343. }
  7344. return nullptr;
  7345. case GGML_OP_RMS_NORM_BACK:
  7346. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7347. return ctx->device->pipeline_rms_norm_back_f32;
  7348. }
  7349. return nullptr;
  7350. case GGML_OP_L2_NORM:
  7351. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7352. return ctx->device->pipeline_l2_norm_f32;
  7353. }
  7354. return nullptr;
  7355. case GGML_OP_UNARY:
  7356. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7357. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7358. (src0->type != dst->type)) {
  7359. return nullptr;
  7360. }
  7361. switch (ggml_get_unary_op(dst)) {
  7362. case GGML_UNARY_OP_EXP:
  7363. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7364. case GGML_UNARY_OP_SILU:
  7365. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7366. case GGML_UNARY_OP_GELU:
  7367. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7368. case GGML_UNARY_OP_GELU_ERF:
  7369. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7370. case GGML_UNARY_OP_GELU_QUICK:
  7371. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7372. case GGML_UNARY_OP_RELU:
  7373. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7374. case GGML_UNARY_OP_XIELU:
  7375. return ctx->device->pipeline_xielu[dst->type == GGML_TYPE_F16];
  7376. case GGML_UNARY_OP_NEG:
  7377. return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16];
  7378. case GGML_UNARY_OP_TANH:
  7379. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7380. case GGML_UNARY_OP_SIGMOID:
  7381. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7382. case GGML_UNARY_OP_HARDSIGMOID:
  7383. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7384. case GGML_UNARY_OP_HARDSWISH:
  7385. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7386. case GGML_UNARY_OP_ABS:
  7387. return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16];
  7388. case GGML_UNARY_OP_SOFTPLUS:
  7389. return ctx->device->pipeline_softplus[dst->type == GGML_TYPE_F16];
  7390. case GGML_UNARY_OP_STEP:
  7391. return ctx->device->pipeline_step[dst->type == GGML_TYPE_F16];
  7392. case GGML_UNARY_OP_ROUND:
  7393. return ctx->device->pipeline_round[dst->type == GGML_TYPE_F16];
  7394. case GGML_UNARY_OP_CEIL:
  7395. return ctx->device->pipeline_ceil[dst->type == GGML_TYPE_F16];
  7396. case GGML_UNARY_OP_FLOOR:
  7397. return ctx->device->pipeline_floor[dst->type == GGML_TYPE_F16];
  7398. case GGML_UNARY_OP_TRUNC:
  7399. return ctx->device->pipeline_trunc[dst->type == GGML_TYPE_F16];
  7400. default:
  7401. break;
  7402. }
  7403. return nullptr;
  7404. case GGML_OP_GLU:
  7405. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7406. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7407. (src0->type != dst->type)) {
  7408. return nullptr;
  7409. }
  7410. switch (ggml_get_glu_op(dst)) {
  7411. case GGML_GLU_OP_GEGLU:
  7412. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7413. case GGML_GLU_OP_REGLU:
  7414. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7415. case GGML_GLU_OP_SWIGLU:
  7416. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7417. case GGML_GLU_OP_SWIGLU_OAI:
  7418. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7419. case GGML_GLU_OP_GEGLU_ERF:
  7420. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7421. case GGML_GLU_OP_GEGLU_QUICK:
  7422. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7423. default:
  7424. break;
  7425. }
  7426. return nullptr;
  7427. case GGML_OP_DIAG_MASK_INF:
  7428. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7429. return ctx->device->pipeline_diag_mask_inf_f32;
  7430. }
  7431. return nullptr;
  7432. case GGML_OP_SOFT_MAX:
  7433. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7434. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7435. if (ctx->num_additional_fused_ops) {
  7436. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7437. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7438. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7439. // use n_experts from push constant if it's not equal to the power of two spec constant
  7440. bool use_push = dst->ne[0] != (1u << idx);
  7441. return ctx->device->pipeline_topk_moe[idx][mode][use_push];
  7442. }
  7443. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7444. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7445. }
  7446. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7447. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7448. }
  7449. return nullptr;
  7450. case GGML_OP_SOFT_MAX_BACK:
  7451. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7452. return ctx->device->pipeline_soft_max_back_f32;
  7453. }
  7454. return nullptr;
  7455. case GGML_OP_ROPE:
  7456. case GGML_OP_ROPE_BACK:
  7457. {
  7458. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7459. const int mode = ((const int32_t *) rope->op_params)[2];
  7460. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7461. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7462. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7463. if (is_neox) {
  7464. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7465. return ctx->device->pipeline_rope_neox_f32;
  7466. }
  7467. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7468. return ctx->device->pipeline_rope_neox_f32_f16;
  7469. }
  7470. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7471. return ctx->device->pipeline_rope_neox_f16;
  7472. }
  7473. } else if (is_mrope && !is_vision) {
  7474. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7475. return ctx->device->pipeline_rope_multi_f32;
  7476. }
  7477. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7478. return ctx->device->pipeline_rope_multi_f32_f16;
  7479. }
  7480. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7481. return ctx->device->pipeline_rope_multi_f16;
  7482. }
  7483. } else if (is_vision) {
  7484. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7485. return ctx->device->pipeline_rope_vision_f32;
  7486. }
  7487. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7488. return ctx->device->pipeline_rope_vision_f16;
  7489. }
  7490. } else {
  7491. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7492. return ctx->device->pipeline_rope_norm_f32;
  7493. }
  7494. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7495. return ctx->device->pipeline_rope_norm_f32_f16;
  7496. }
  7497. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7498. return ctx->device->pipeline_rope_norm_f16;
  7499. }
  7500. }
  7501. return nullptr;
  7502. }
  7503. case GGML_OP_SUM:
  7504. case GGML_OP_SUM_ROWS:
  7505. case GGML_OP_MEAN:
  7506. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7507. return ctx->device->pipeline_sum_rows_f32;
  7508. }
  7509. return nullptr;
  7510. case GGML_OP_CUMSUM:
  7511. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7512. return ctx->device->pipeline_cumsum_f32;
  7513. }
  7514. return nullptr;
  7515. case GGML_OP_SOLVE_TRI:
  7516. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7517. vk_solve_tri_pipeline_state solve_tri_pipeline_state(src0->ne[0], src1->ne[0]);
  7518. vk_pipeline pipeline = nullptr;
  7519. {
  7520. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7521. auto it = ctx->device->pipeline_solve_tri_f32.find(solve_tri_pipeline_state);
  7522. if (it != ctx->device->pipeline_solve_tri_f32.end()) {
  7523. pipeline = it->second;
  7524. } else {
  7525. ctx->device->pipeline_solve_tri_f32[solve_tri_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7526. }
  7527. }
  7528. return pipeline;
  7529. }
  7530. return nullptr;
  7531. case GGML_OP_ARGMAX:
  7532. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7533. return ctx->device->pipeline_argmax_f32;
  7534. }
  7535. return nullptr;
  7536. case GGML_OP_COUNT_EQUAL:
  7537. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7538. return ctx->device->pipeline_count_equal_i32;
  7539. }
  7540. return nullptr;
  7541. case GGML_OP_IM2COL:
  7542. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7543. return ctx->device->pipeline_im2col_f32;
  7544. }
  7545. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7546. return ctx->device->pipeline_im2col_f32_f16;
  7547. }
  7548. return nullptr;
  7549. case GGML_OP_IM2COL_3D:
  7550. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7551. return ctx->device->pipeline_im2col_3d_f32;
  7552. }
  7553. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7554. return ctx->device->pipeline_im2col_3d_f32_f16;
  7555. }
  7556. return nullptr;
  7557. case GGML_OP_TIMESTEP_EMBEDDING:
  7558. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7559. return ctx->device->pipeline_timestep_embedding_f32;
  7560. }
  7561. return nullptr;
  7562. case GGML_OP_CONV_TRANSPOSE_1D:
  7563. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7564. return ctx->device->pipeline_conv_transpose_1d_f32;
  7565. }
  7566. return nullptr;
  7567. case GGML_OP_POOL_2D:
  7568. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7569. return ctx->device->pipeline_pool2d_f32;
  7570. }
  7571. return nullptr;
  7572. case GGML_OP_RWKV_WKV6:
  7573. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7574. return ctx->device->pipeline_rwkv_wkv6_f32;
  7575. }
  7576. return nullptr;
  7577. case GGML_OP_RWKV_WKV7:
  7578. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7579. return ctx->device->pipeline_rwkv_wkv7_f32;
  7580. }
  7581. return nullptr;
  7582. case GGML_OP_SSM_SCAN:
  7583. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7584. const uint32_t d_state = src0->ne[0];
  7585. if (d_state == 128) {
  7586. return ctx->device->pipeline_ssm_scan_f32_d128;
  7587. } else if (d_state == 256) {
  7588. return ctx->device->pipeline_ssm_scan_f32_d256;
  7589. }
  7590. }
  7591. return nullptr;
  7592. case GGML_OP_SSM_CONV:
  7593. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7594. return ctx->device->pipeline_ssm_conv_f32;
  7595. }
  7596. return nullptr;
  7597. case GGML_OP_OPT_STEP_ADAMW:
  7598. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7599. return ctx->device->pipeline_opt_step_adamw_f32;
  7600. }
  7601. return nullptr;
  7602. case GGML_OP_OPT_STEP_SGD:
  7603. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7604. return ctx->device->pipeline_opt_step_sgd_f32;
  7605. }
  7606. return nullptr;
  7607. case GGML_OP_LEAKY_RELU:
  7608. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7609. return ctx->device->pipeline_leaky_relu_f32;
  7610. }
  7611. return nullptr;
  7612. case GGML_OP_CONV_2D:
  7613. case GGML_OP_CONV_TRANSPOSE_2D:
  7614. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7615. uint32_t K = dst->ne[2]; // Cout
  7616. uint32_t NPQ = dst->ne[3] * dst->ne[1] * dst->ne[0]; // N * OH * OW
  7617. vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, K, NPQ);
  7618. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  7619. uint32_t KW = (uint32_t)src0->ne[0];
  7620. uint32_t KH = (uint32_t)src0->ne[1];
  7621. uint32_t s0 = (uint32_t)(ggml_get_op_params_i32(dst, 0));
  7622. uint32_t s1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 1) : s0;
  7623. uint32_t p0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0;
  7624. uint32_t p1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 3) : 0;
  7625. uint32_t d0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 4) : 1;
  7626. uint32_t d1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 5) : 1;
  7627. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7628. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7629. if (op == GGML_OP_CONV_2D) {
  7630. if (src0->type == GGML_TYPE_F32) {
  7631. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7632. } else if (src0->type == GGML_TYPE_F16) {
  7633. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7634. }
  7635. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7636. if (src0->type == GGML_TYPE_F32) {
  7637. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7638. } else if (src0->type == GGML_TYPE_F16) {
  7639. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7640. }
  7641. }
  7642. vk_pipeline pipeline = nullptr;
  7643. {
  7644. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7645. auto it = pipelines->find(conv2d_pipeline_state);
  7646. if (it != pipelines->end()) {
  7647. pipeline = it->second;
  7648. } else {
  7649. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7650. }
  7651. }
  7652. return pipeline;
  7653. }
  7654. return nullptr;
  7655. case GGML_OP_CONV_2D_DW:
  7656. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7657. if (ggml_is_contiguous(src1)) {
  7658. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7659. } else if (ggml_is_contiguous_channels(src1)) {
  7660. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7661. }
  7662. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7663. if (ggml_is_contiguous(src1)) {
  7664. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7665. } else if (ggml_is_contiguous_channels(src1)) {
  7666. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7667. }
  7668. }
  7669. return nullptr;
  7670. case GGML_OP_ADD1:
  7671. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7672. return ctx->device->pipeline_add1_f16_f16;
  7673. }
  7674. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7675. return ctx->device->pipeline_add1_f16_f32;
  7676. }
  7677. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7678. return ctx->device->pipeline_add1_f32_f32;
  7679. }
  7680. return nullptr;
  7681. case GGML_OP_ARANGE:
  7682. if (dst->type == GGML_TYPE_F32) {
  7683. return ctx->device->pipeline_arange_f32;
  7684. }
  7685. return nullptr;
  7686. case GGML_OP_FILL:
  7687. if (dst->type == GGML_TYPE_F32) {
  7688. return ctx->device->pipeline_fill_f32;
  7689. }
  7690. return nullptr;
  7691. default:
  7692. return nullptr;
  7693. }
  7694. GGML_UNUSED(src2);
  7695. }
  7696. 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) {
  7697. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7698. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7699. p.misalign_offsets = (a_offset << 16) | d_offset;
  7700. GGML_UNUSED(src1);
  7701. GGML_UNUSED(src2);
  7702. GGML_UNUSED(src3);
  7703. }
  7704. 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) {
  7705. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7706. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7707. p.misalign_offsets = (a_offset << 16) | d_offset;
  7708. GGML_UNUSED(src1);
  7709. GGML_UNUSED(src2);
  7710. GGML_UNUSED(src3);
  7711. }
  7712. 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) {
  7713. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7714. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7715. p.misalign_offsets = (a_offset << 16) | d_offset;
  7716. GGML_UNUSED(src1);
  7717. GGML_UNUSED(src2);
  7718. GGML_UNUSED(src3);
  7719. }
  7720. 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) {
  7721. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7722. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7723. p.misalign_offsets = (a_offset << 16) | d_offset;
  7724. GGML_UNUSED(src0);
  7725. GGML_UNUSED(src2);
  7726. GGML_UNUSED(src3);
  7727. }
  7728. 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) {
  7729. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7730. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7731. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7732. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7733. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7734. GGML_UNUSED(src2);
  7735. GGML_UNUSED(src3);
  7736. }
  7737. 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) {
  7738. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7739. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7740. p.a_offset = a_offset;
  7741. p.d_offset = d_offset;
  7742. GGML_UNUSED(src1);
  7743. GGML_UNUSED(src2);
  7744. GGML_UNUSED(src3);
  7745. }
  7746. template<typename PC>
  7747. 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) {
  7748. 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];
  7749. if (src1 != nullptr) {
  7750. 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];
  7751. }
  7752. if (src2 != nullptr) {
  7753. 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];
  7754. }
  7755. if (src3 != nullptr) {
  7756. 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];
  7757. }
  7758. 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];
  7759. std::cerr << "), " << ggml_op_name(op) << ")");
  7760. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7761. GGML_ASSERT(dst->buffer != nullptr);
  7762. const uint64_t ne00 = src0->ne[0];
  7763. const uint64_t ne01 = src0->ne[1];
  7764. const uint64_t ne02 = src0->ne[2];
  7765. const uint64_t ne03 = src0->ne[3];
  7766. const bool use_src1 = src1 != nullptr;
  7767. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7768. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7769. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7770. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7771. const bool use_src2 = src2 != nullptr;
  7772. const bool use_src3 = src3 != nullptr;
  7773. init_pushconst_fastdiv(pc);
  7774. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7775. if (pipeline == nullptr) {
  7776. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7777. if (src1 != nullptr) {
  7778. std::cerr << " and " << ggml_type_name(src1->type);
  7779. }
  7780. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7781. GGML_ABORT("fatal error");
  7782. }
  7783. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7784. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true);
  7785. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, true) : vk_subbuffer{};
  7786. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, true) : vk_subbuffer{};
  7787. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, true) : vk_subbuffer{};
  7788. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
  7789. // Compute misalignment offset for descriptors and store it in in push constants.
  7790. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7791. std::array<uint32_t, 3> elements;
  7792. switch (op) {
  7793. case GGML_OP_NORM:
  7794. case GGML_OP_RMS_NORM_BACK:
  7795. case GGML_OP_L2_NORM:
  7796. case GGML_OP_SOFT_MAX:
  7797. case GGML_OP_SOFT_MAX_BACK:
  7798. case GGML_OP_SUM_ROWS:
  7799. case GGML_OP_CUMSUM:
  7800. case GGML_OP_MEAN:
  7801. case GGML_OP_ARGMAX:
  7802. {
  7803. const uint32_t nr = ggml_nrows(src0);
  7804. if (nr > 262144) {
  7805. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7806. } else if (nr > 512) {
  7807. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7808. } else {
  7809. elements = { nr, 1, 1 };
  7810. }
  7811. } break;
  7812. case GGML_OP_SOLVE_TRI:
  7813. {
  7814. uint32_t nr = (uint32_t)(ne02 * ne03);
  7815. if (nr > 262144) {
  7816. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7817. } else if (nr > 512) {
  7818. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7819. } else {
  7820. elements = { nr, 1, 1 };
  7821. }
  7822. }
  7823. break;
  7824. case GGML_OP_RMS_NORM:
  7825. if (ctx->do_add_rms_partials) {
  7826. // Run one element per thread, 128 threads per workgroup
  7827. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7828. } else {
  7829. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7830. }
  7831. break;
  7832. case GGML_OP_SUM:
  7833. // We use GGML_OP_SUM_ROWS with 1 row.
  7834. elements = { 1, 1, 1 };
  7835. break;
  7836. case GGML_OP_GROUP_NORM:
  7837. {
  7838. const uint32_t num_groups = dst->op_params[0];
  7839. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7840. } break;
  7841. case GGML_OP_DIAG_MASK_INF:
  7842. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7843. break;
  7844. case GGML_OP_ROPE:
  7845. case GGML_OP_ROPE_BACK:
  7846. {
  7847. uint32_t nrows = (uint32_t)ggml_nrows(src0);
  7848. uint32_t z = 1;
  7849. if (nrows > ctx->device->properties.limits.maxComputeWorkGroupCount[0]) {
  7850. z = CEIL_DIV(nrows, 32768);
  7851. nrows = 32768;
  7852. }
  7853. elements = { nrows, (uint32_t)ne00, z };
  7854. } break;
  7855. case GGML_OP_GET_ROWS:
  7856. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7857. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7858. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7859. break;
  7860. case GGML_OP_ARGSORT:
  7861. GGML_ASSERT(0);
  7862. break;
  7863. case GGML_OP_IM2COL:
  7864. {
  7865. const bool is_2D = dst->op_params[6] == 1;
  7866. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7867. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7868. const uint32_t KW = src0->ne[0];
  7869. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7870. const uint32_t OW = dst->ne[1];
  7871. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7872. elements = { OW * KW * KH, OH, batch * IC };
  7873. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7874. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7875. } break;
  7876. case GGML_OP_IM2COL_3D:
  7877. {
  7878. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7879. const uint32_t N = ne13 / IC;
  7880. const uint32_t KD = ne02;
  7881. const uint32_t KH = ne01;
  7882. const uint32_t KW = ne00;
  7883. const uint32_t OD = dst->ne[3] / N;
  7884. const uint32_t OH = dst->ne[2];
  7885. const uint32_t OW = dst->ne[1];
  7886. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7887. const uint32_t N_OD_OH = N*OD*OH;
  7888. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7889. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7890. } break;
  7891. case GGML_OP_TIMESTEP_EMBEDDING:
  7892. {
  7893. const uint32_t dim = dst->op_params[0];
  7894. uint32_t half_ceil = (dim + 1) / 2;
  7895. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7896. } break;
  7897. case GGML_OP_CONV_TRANSPOSE_1D:
  7898. {
  7899. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7900. } break;
  7901. case GGML_OP_POOL_2D:
  7902. {
  7903. const uint32_t N = dst->ne[3];
  7904. const uint32_t OC = dst->ne[2];
  7905. const uint32_t OH = dst->ne[1];
  7906. const uint32_t OW = dst->ne[0];
  7907. elements = { N * OC * OH * OW, 1, 1};
  7908. } break;
  7909. case GGML_OP_CONV_2D:
  7910. case GGML_OP_CONV_TRANSPOSE_2D:
  7911. if constexpr (std::is_same_v<PC, vk_op_conv2d_push_constants>) {
  7912. const uint32_t NPQ = pc.N * pc.OH * pc.OW;
  7913. const vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, pc.Cout, NPQ);
  7914. const uint32_t NPQ_blocks = CEIL_DIV(NPQ, vk_conv_block_sizes[shape].NPQ);
  7915. elements = { pc.Cout, NPQ_blocks, 1 };
  7916. if (elements[1] > 512) {
  7917. elements[2] = CEIL_DIV(elements[1], 512);
  7918. elements[1] = 512;
  7919. }
  7920. } else {
  7921. GGML_ABORT("invalid push constant type for CONV_2D");
  7922. }
  7923. break;
  7924. case GGML_OP_ADD:
  7925. case GGML_OP_SUB:
  7926. case GGML_OP_DIV:
  7927. case GGML_OP_MUL:
  7928. case GGML_OP_ADD1:
  7929. case GGML_OP_ARANGE:
  7930. case GGML_OP_FILL:
  7931. case GGML_OP_SCALE:
  7932. case GGML_OP_SQR:
  7933. case GGML_OP_SQRT:
  7934. case GGML_OP_SIN:
  7935. case GGML_OP_COS:
  7936. case GGML_OP_LOG:
  7937. case GGML_OP_TRI:
  7938. case GGML_OP_DIAG:
  7939. case GGML_OP_CLAMP:
  7940. case GGML_OP_PAD:
  7941. case GGML_OP_ROLL:
  7942. case GGML_OP_REPEAT:
  7943. case GGML_OP_REPEAT_BACK:
  7944. case GGML_OP_CPY:
  7945. case GGML_OP_CONCAT:
  7946. case GGML_OP_UPSCALE:
  7947. case GGML_OP_UNARY:
  7948. case GGML_OP_GLU:
  7949. case GGML_OP_CONV_2D_DW:
  7950. {
  7951. uint32_t ne = ggml_nelements(dst);
  7952. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7953. // Convert from number of logical elements to 2- or 4-byte units.
  7954. ne /= ggml_blck_size(src0->type);
  7955. if ((ggml_type_size(src0->type) % 4) == 0) {
  7956. ne *= ggml_type_size(src0->type) / 4;
  7957. } else {
  7958. ne *= ggml_type_size(src0->type) / 2;
  7959. }
  7960. }
  7961. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7962. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7963. // So divide by block size here before splitting into 512x512 groups.
  7964. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7965. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7966. }
  7967. if (ne > 262144) {
  7968. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7969. } else if (ne > 512) {
  7970. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7971. } else {
  7972. elements = { ne, 1, 1 };
  7973. }
  7974. if (pipeline == ctx->device->pipeline_cpy_transpose_32 ||
  7975. pipeline == ctx->device->pipeline_cpy_transpose_16) {
  7976. // 32x32 tiles
  7977. elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32);
  7978. elements[1] = (uint32_t)CEIL_DIV(dst->ne[1], 32);
  7979. elements[2] = (uint32_t)(dst->ne[2]*dst->ne[3]);
  7980. elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]);
  7981. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7982. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7983. }
  7984. } break;
  7985. case GGML_OP_ADD_ID:
  7986. {
  7987. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7988. } break;
  7989. case GGML_OP_SET_ROWS:
  7990. {
  7991. uint32_t ne = ggml_nelements(src0);
  7992. if (ggml_is_quantized(dst->type)) {
  7993. // quants run 32 threads each doing QUANT_K elements
  7994. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7995. } else {
  7996. // scalar types do one element per thread, running 512 threads
  7997. ne = CEIL_DIV(ne, 512);
  7998. }
  7999. if (ne > 262144) {
  8000. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8001. } else if (ne > 512) {
  8002. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8003. } else {
  8004. elements = { ne, 1, 1 };
  8005. }
  8006. }
  8007. break;
  8008. case GGML_OP_SSM_CONV:
  8009. {
  8010. const uint32_t nr = src0->ne[1];
  8011. const uint32_t n_t = dst->ne[1];
  8012. const uint32_t n_s = dst->ne[2];
  8013. elements = { nr, n_t, n_s };
  8014. }
  8015. break;
  8016. default:
  8017. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  8018. break;
  8019. }
  8020. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  8021. vk_subbuffer a_buf = src0_buf;
  8022. if (ctx->do_add_rms_partials) {
  8023. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  8024. }
  8025. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8026. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  8027. } else if (op == GGML_OP_GLU) {
  8028. // Empty src1 is possible in glu, but the shader needs a buffer
  8029. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  8030. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  8031. } else if (op == GGML_OP_SOFT_MAX) {
  8032. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  8033. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  8034. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  8035. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  8036. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  8037. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  8038. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  8039. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  8040. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  8041. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  8042. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  8043. // buffer device address path doesn't use dst buffer
  8044. dst_buf.size = 1;
  8045. }
  8046. // im2col uses only src1 and dst buffers
  8047. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  8048. } else if (op == GGML_OP_COUNT_EQUAL) {
  8049. // count_equal assumes that destination buffer is initialized with zeroes
  8050. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  8051. ggml_vk_sync_buffers(ctx, subctx);
  8052. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  8053. } else if (op == GGML_OP_OPT_STEP_SGD) {
  8054. // OPT_STEP_SGD works on src0, it does not need dst
  8055. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  8056. } else if (use_src3) {
  8057. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  8058. } else if (use_src2) {
  8059. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  8060. } else if (use_src1) {
  8061. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  8062. } else {
  8063. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  8064. }
  8065. }
  8066. 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) {
  8067. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8068. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8069. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8070. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  8071. (uint32_t)ggml_nelements(src0),
  8072. (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,
  8073. (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,
  8074. (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,
  8075. 0,
  8076. 0.0f, 0.0f, 0,
  8077. });
  8078. }
  8079. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8080. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8081. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8082. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8083. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  8084. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  8085. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  8086. int offset = dst->op_params[3] / 4; // offset in bytes
  8087. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  8088. (uint32_t)ggml_nelements(src0),
  8089. (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,
  8090. (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,
  8091. (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,
  8092. 0,
  8093. 0.0f, 0.0f, offset,
  8094. });
  8095. }
  8096. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8097. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  8098. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  8099. // Make a list of all the tensors used by the op.
  8100. // Last element of the list is the dest tensor.
  8101. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  8102. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  8103. uint32_t num_tensors = num_srcs + 1;
  8104. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  8105. tensors[0] = first_node->src[0];
  8106. tensors[1] = first_node->src[1];
  8107. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  8108. // check whether the previous result is src[0] or src[1]
  8109. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  8110. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  8111. } else {
  8112. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  8113. }
  8114. }
  8115. tensors[num_srcs] = dst;
  8116. vk_op_multi_add_push_constants pc;
  8117. pc.ne20 = (uint32_t)dst->ne[0];
  8118. pc.ne21 = (uint32_t)dst->ne[1];
  8119. pc.ne22 = (uint32_t)dst->ne[2];
  8120. pc.ne23 = (uint32_t)dst->ne[3];
  8121. for (uint32_t i = 0; i < num_tensors; ++i) {
  8122. const ggml_tensor *t = tensors[i];
  8123. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  8124. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  8125. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  8126. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  8127. }
  8128. pc.rms_partials = ctx->do_add_rms_partials;
  8129. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  8130. if (pipeline == nullptr) {
  8131. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  8132. GGML_ABORT("fatal error");
  8133. }
  8134. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8135. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  8136. vk_buffer buf[MAX_PARAMETER_COUNT];
  8137. size_t offset[MAX_PARAMETER_COUNT];
  8138. bool uma[MAX_PARAMETER_COUNT];
  8139. for (uint32_t i = 0; i < num_tensors; ++i) {
  8140. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8141. buf[i] = nullptr;
  8142. offset[i] = 0;
  8143. uma[i] = false;
  8144. if (ctx->device->uma) {
  8145. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8146. uma[i] = buf[i] != nullptr;
  8147. }
  8148. if (!uma[i]) {
  8149. buf[i] = buf_ctx[i]->dev_buffer;
  8150. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8151. }
  8152. GGML_ASSERT(buf[i] != nullptr);
  8153. }
  8154. // If any remaining descriptors are unused, just point them at src[0]
  8155. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  8156. buf[i] = buf[0];
  8157. offset[i] = 0;
  8158. }
  8159. if (ctx->do_add_rms_partials) {
  8160. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  8161. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  8162. }
  8163. std::array<uint32_t, 3> elements;
  8164. uint32_t ne = ggml_nelements(dst);
  8165. if (ne > 262144) {
  8166. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8167. } else if (ne > 512) {
  8168. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8169. } else {
  8170. elements = { ne, 1, 1 };
  8171. }
  8172. static_assert(MAX_PARAMETER_COUNT == 12);
  8173. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8174. {
  8175. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8176. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8177. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8178. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8179. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8180. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8181. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8182. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  8183. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  8184. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  8185. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  8186. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  8187. }, pc, elements);
  8188. }
  8189. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8190. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8191. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8192. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8193. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  8194. (uint32_t)ggml_nelements(src0),
  8195. (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,
  8196. (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,
  8197. (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,
  8198. 0,
  8199. 0.0f, 0.0f, ctx->do_add_rms_partials,
  8200. });
  8201. }
  8202. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8203. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8204. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8205. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8206. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  8207. (uint32_t)ggml_nelements(src0),
  8208. (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,
  8209. (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,
  8210. (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,
  8211. 0,
  8212. 0.0f, 0.0f, 0,
  8213. });
  8214. }
  8215. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8216. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8217. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8218. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8219. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  8220. (uint32_t)ggml_nelements(src0),
  8221. (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,
  8222. (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,
  8223. (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,
  8224. 0,
  8225. 0.0f, 0.0f, 0,
  8226. });
  8227. }
  8228. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8229. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8230. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8231. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8232. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  8233. (uint32_t)ggml_nelements(src0),
  8234. (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,
  8235. (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,
  8236. (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,
  8237. 0,
  8238. 0.0f, 0.0f, 0,
  8239. });
  8240. }
  8241. 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) {
  8242. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8243. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8244. const uint32_t src2_type_size = ggml_type_size(src2->type);
  8245. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  8246. (uint32_t)dst->ne[0],
  8247. (uint32_t)dst->ne[1],
  8248. (uint32_t)src0->nb[1] / src0_type_size,
  8249. (uint32_t)src0->nb[2] / src0_type_size,
  8250. (uint32_t)src1->nb[1] / src1_type_size,
  8251. (uint32_t)src2->nb[1] / src2_type_size,
  8252. });
  8253. }
  8254. 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) {
  8255. GGML_ASSERT(version == 6 || version == 7);
  8256. int num_srcs = version == 6 ? 6 : 7;
  8257. for (int i = 0; i < num_srcs; i++) {
  8258. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  8259. }
  8260. GGML_ASSERT(dst->buffer != nullptr);
  8261. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8262. GGML_ASSERT(pipeline != nullptr);
  8263. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8264. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8265. vk_subbuffer src_buf[7] = {};
  8266. for (int i = 0; i < num_srcs; i++) {
  8267. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8268. }
  8269. std::array<uint32_t, 3> elements = {
  8270. (uint32_t)(pc.B * pc.H),
  8271. 1,
  8272. 1
  8273. };
  8274. if (version == 6) {
  8275. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8276. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  8277. pc, elements);
  8278. } else if (version == 7) {
  8279. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8280. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8281. pc, elements);
  8282. } else {
  8283. // shouldn't happen
  8284. GGML_ASSERT(false);
  8285. }
  8286. }
  8287. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8288. const size_t seq_length = dst->src[0]->ne[2];
  8289. const size_t n_embed = dst->ne[0];
  8290. const size_t n_heads = dst->src[0]->ne[1];
  8291. const size_t n_seqs = dst->src[5]->ne[1];
  8292. ggml_vk_op_f32_wkv(
  8293. ctx, subctx, dst,
  8294. {
  8295. (uint32_t)n_seqs,
  8296. (uint32_t)seq_length,
  8297. (uint32_t)n_embed,
  8298. (uint32_t)n_heads,
  8299. },
  8300. 6
  8301. );
  8302. }
  8303. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8304. const size_t seq_length = dst->src[0]->ne[2];
  8305. const size_t n_embed = dst->ne[0];
  8306. const size_t n_heads = dst->src[0]->ne[1];
  8307. const size_t n_seqs = dst->src[6]->ne[1];
  8308. ggml_vk_op_f32_wkv(
  8309. ctx, subctx, dst,
  8310. {
  8311. (uint32_t)n_seqs,
  8312. (uint32_t)seq_length,
  8313. (uint32_t)n_embed,
  8314. (uint32_t)n_heads,
  8315. },
  8316. 7
  8317. );
  8318. }
  8319. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8320. const ggml_tensor * src0 = dst->src[0];
  8321. const ggml_tensor * src1 = dst->src[1];
  8322. const ggml_tensor * src2 = dst->src[2];
  8323. const ggml_tensor * src3 = dst->src[3];
  8324. const ggml_tensor * src4 = dst->src[4];
  8325. const ggml_tensor * src5 = dst->src[5];
  8326. GGML_ASSERT(dst->buffer != nullptr);
  8327. const uint32_t head_dim = src0->ne[1];
  8328. const uint32_t n_head = src1->ne[1];
  8329. const uint32_t n_group = src4->ne[1];
  8330. const uint32_t n_tok = src1->ne[2];
  8331. const uint32_t n_seq = src1->ne[3];
  8332. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8333. GGML_ASSERT(is_mamba2);
  8334. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8335. GGML_ASSERT(pipeline != nullptr);
  8336. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8337. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8338. const vk_op_ssm_scan_push_constants pc = {
  8339. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8340. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8341. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8342. (uint32_t)src3->nb[1],
  8343. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8344. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8345. (uint32_t)s_off,
  8346. n_head, head_dim, n_group, n_tok
  8347. };
  8348. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8349. vk_subbuffer src_buf[7] = {};
  8350. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8351. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8352. }
  8353. std::array<uint32_t, 3> elements;
  8354. const int splitH = 16;
  8355. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8356. const uint32_t num_workgroups_y = n_seq;
  8357. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8358. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8359. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8360. pc, elements);
  8361. }
  8362. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8363. const ggml_tensor * src0 = dst->src[0];
  8364. const ggml_tensor * src1 = dst->src[1];
  8365. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8366. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8367. (uint32_t)src1->nb[1],
  8368. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8369. (uint32_t)src1->ne[0],
  8370. (uint32_t)src0->ne[0],
  8371. (uint32_t)src0->ne[1],
  8372. (uint32_t)dst->ne[1],
  8373. (uint32_t)dst->ne[2],
  8374. });
  8375. }
  8376. 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) {
  8377. const ggml_tensor * x = dst->src[0];
  8378. const ggml_tensor * g = dst->src[1];
  8379. const ggml_tensor * gm = dst->src[2];
  8380. const ggml_tensor * gv = dst->src[3];
  8381. const ggml_tensor * p = dst->src[4];
  8382. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8383. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8384. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8385. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8386. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8387. GGML_ASSERT(dst->buffer != nullptr);
  8388. GGML_ASSERT(ggml_is_contiguous(x));
  8389. GGML_ASSERT(ggml_is_contiguous(g));
  8390. GGML_ASSERT(ggml_is_contiguous(gm));
  8391. GGML_ASSERT(ggml_is_contiguous(gv));
  8392. GGML_ASSERT(ggml_is_contiguous(p));
  8393. GGML_ASSERT(ggml_are_same_shape(x, g));
  8394. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8395. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8396. GGML_ASSERT(ggml_nelements(p) == 7);
  8397. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8398. GGML_ASSERT(pipeline != nullptr);
  8399. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8400. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8401. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8402. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8403. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8404. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8405. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8406. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8407. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8408. pc, elements);
  8409. }
  8410. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8411. const size_t n = ggml_nelements(dst->src[0]);
  8412. ggml_vk_op_f32_opt_step_adamw(
  8413. ctx, subctx, dst,
  8414. { (uint32_t)n, 0, 0.0f, 0.0f, 0.0f, 0.0f }
  8415. );
  8416. }
  8417. 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) {
  8418. const size_t n = ggml_nelements(dst->src[0]);
  8419. 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 });
  8420. }
  8421. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8422. int * op_params = (int *)dst->op_params;
  8423. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8424. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8425. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8426. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8427. (uint32_t)ggml_nelements(dst),
  8428. (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,
  8429. (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,
  8430. (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,
  8431. 0,
  8432. 0.0f, 0.0f, op_params[0],
  8433. });
  8434. }
  8435. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8436. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8437. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8438. GGML_TENSOR_UNARY_OP_LOCALS
  8439. float sf0 = (float)ne0 / ne00;
  8440. float sf1 = (float)ne1 / ne01;
  8441. float sf2 = (float)ne2 / ne02;
  8442. float sf3 = (float)ne3 / ne03;
  8443. float pixel_offset = 0.5f;
  8444. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8445. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8446. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8447. pixel_offset = 0.0f;
  8448. }
  8449. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8450. (uint32_t)ggml_nelements(dst), 0, 0,
  8451. (uint32_t)ne00, (uint32_t)ne01,
  8452. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8453. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8454. sf0, sf1, sf2, sf3, pixel_offset
  8455. });
  8456. }
  8457. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8458. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8459. p.param1 = ggml_get_op_params_f32(dst, 0);
  8460. p.param2 = ggml_get_op_params_f32(dst, 1);
  8461. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8462. }
  8463. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8464. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8465. }
  8466. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8467. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8468. }
  8469. static void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8470. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8471. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8472. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8473. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, {
  8474. (uint32_t)ggml_nelements(src0),
  8475. (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,
  8476. (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,
  8477. (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,
  8478. 0,
  8479. 0.0f, 0.0f, 0,
  8480. });
  8481. }
  8482. static void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8483. VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8484. vk_op_push_constants pc = {
  8485. (uint32_t)ggml_nelements(dst),
  8486. 1,
  8487. ggml_get_op_params_f32(dst, 0),
  8488. ggml_get_op_params_f32(dst, 2),
  8489. 0.0f, 0.0f,
  8490. };
  8491. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_ARANGE);
  8492. GGML_ASSERT(pipeline != nullptr);
  8493. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8494. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8495. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8496. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8497. }
  8498. static void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8499. VK_LOG_DEBUG("ggml_vk_fill(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8500. vk_op_push_constants pc = {
  8501. (uint32_t)ggml_nelements(dst),
  8502. 1,
  8503. ggml_get_op_params_f32(dst, 0),
  8504. 0.0f,
  8505. 0.0f, 0.0f,
  8506. };
  8507. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_FILL);
  8508. GGML_ASSERT(pipeline != nullptr);
  8509. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8510. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8511. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8512. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8513. }
  8514. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8515. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8516. }
  8517. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8518. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8519. }
  8520. static void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8521. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst));
  8522. }
  8523. static void ggml_vk_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8524. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8525. p.param1 = ggml_get_op_params_f32(dst, 0);
  8526. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TRI, std::move(p));
  8527. }
  8528. static void ggml_vk_diag(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8529. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8530. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG, std::move(p));
  8531. }
  8532. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8533. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8534. p.param1 = ggml_get_op_params_f32(dst, 0);
  8535. p.param2 = ggml_get_op_params_f32(dst, 1);
  8536. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8537. }
  8538. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8539. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8540. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8541. }
  8542. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8543. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8544. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8545. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8546. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8547. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8548. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8549. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8550. memcpy(&p.param1, &s01_packed, sizeof(float));
  8551. memcpy(&p.param2, &s23_packed, sizeof(float));
  8552. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8553. }
  8554. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8555. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8556. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8557. }
  8558. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8559. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8560. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8561. }
  8562. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8563. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8564. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8565. // Convert from number of logical elements to 2- or 4-byte units.
  8566. ne /= ggml_blck_size(src0->type);
  8567. if ((ggml_type_size(src0->type) % 4) == 0) {
  8568. ne *= ggml_type_size(src0->type) / 4;
  8569. } else {
  8570. ne *= ggml_type_size(src0->type) / 2;
  8571. }
  8572. }
  8573. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8574. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8575. }
  8576. 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) {
  8577. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8578. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8579. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8580. // Skip empty skip_rows operations. For most ops the empty check at the start
  8581. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8582. // with empty srcs.
  8583. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8584. return;
  8585. }
  8586. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8587. (uint32_t)ggml_nelements(src0),
  8588. (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,
  8589. (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,
  8590. (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,
  8591. 0,
  8592. 0.0f, 0.0f, 0,
  8593. });
  8594. }
  8595. 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) {
  8596. 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 });
  8597. }
  8598. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8599. float * op_params = (float *)dst->op_params;
  8600. 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 });
  8601. }
  8602. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8603. const int * int_op_params = (const int *)dst->op_params;
  8604. const float * float_op_params = (const float *)dst->op_params;
  8605. const uint32_t num_groups = int_op_params[0];
  8606. const float eps = float_op_params[1];
  8607. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8608. 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 });
  8609. }
  8610. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8611. const uint32_t ne = (uint32_t)node->ne[0];
  8612. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8613. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8614. return num_partials;
  8615. }
  8616. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8617. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8618. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8619. return num_bytes;
  8620. }
  8621. 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) {
  8622. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8623. const int mode = ((const int32_t *) dst->op_params)[2];
  8624. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8625. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8626. const float freq_base = ((const float *) dst->op_params)[5];
  8627. const float freq_scale = ((const float *) dst->op_params)[6];
  8628. const float ext_factor = ((const float *) dst->op_params)[7];
  8629. const float attn_factor = ((const float *) dst->op_params)[8];
  8630. const float beta_fast = ((const float *) dst->op_params)[9];
  8631. const float beta_slow = ((const float *) dst->op_params)[10];
  8632. int sections[4] {};
  8633. if (mode & GGML_ROPE_TYPE_MROPE) {
  8634. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8635. }
  8636. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8637. float corr_dims[2];
  8638. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8639. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8640. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8641. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8642. vk_op_rope_push_constants rope {
  8643. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8644. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8645. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8646. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8647. };
  8648. return rope;
  8649. }
  8650. 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) {
  8651. ggml_tensor * dst;
  8652. const ggml_tensor * src0;
  8653. const ggml_tensor * src1;
  8654. if (ctx->num_additional_fused_ops > 0) {
  8655. // fused rms_norm + mul
  8656. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8657. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8658. dst = mul;
  8659. src0 = cgraph->nodes[node_idx]->src[0];
  8660. src1 = other_src;
  8661. } else {
  8662. dst = cgraph->nodes[node_idx];
  8663. src0 = src1 = dst->src[0];
  8664. }
  8665. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8666. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8667. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8668. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8669. vk_op_binary_push_constants bin {
  8670. (uint32_t)ggml_nelements(src0),
  8671. (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,
  8672. (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,
  8673. (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,
  8674. 0,
  8675. op_params[0], 0.0f, (int32_t)param3,
  8676. };
  8677. // more than one fused op means rms_norm+mul+rope
  8678. if (ctx->num_additional_fused_ops > 1) {
  8679. static constexpr uint32_t max_tensors = 7;
  8680. const ggml_tensor *tensors[max_tensors] {};
  8681. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8682. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8683. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8684. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8685. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8686. tensors[0] = rms->src[0];
  8687. tensors[1] = other_src;
  8688. tensors[2] = mul;
  8689. tensors[3] = rope->src[1]; // pos
  8690. tensors[4] = rope->src[2]; // ff
  8691. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8692. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8693. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8694. vk_op_rms_norm_mul_rope_push_constants pc;
  8695. pc.bin = bin;
  8696. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8697. 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;
  8698. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8699. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8700. vk_buffer buf[max_tensors];
  8701. size_t offset[max_tensors];
  8702. bool uma[max_tensors];
  8703. for (uint32_t i = 0; i < max_tensors; ++i) {
  8704. if (!tensors[i]) {
  8705. // If any remaining descriptors are unused, just point them at src[0]
  8706. buf[i] = buf[0];
  8707. offset[i] = 0;
  8708. continue;
  8709. }
  8710. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8711. buf[i] = nullptr;
  8712. offset[i] = 0;
  8713. uma[i] = false;
  8714. if (ctx->device->uma) {
  8715. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8716. uma[i] = buf[i] != nullptr;
  8717. }
  8718. if (!uma[i]) {
  8719. buf[i] = buf_ctx[i]->dev_buffer;
  8720. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8721. }
  8722. GGML_ASSERT(buf[i] != nullptr);
  8723. }
  8724. std::array<uint32_t, 3> elements;
  8725. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8726. static_assert(max_tensors == 7);
  8727. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8728. {
  8729. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8730. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8731. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8732. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8733. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8734. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8735. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8736. }, pc, elements);
  8737. } else {
  8738. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8739. }
  8740. if (ctx->do_add_rms_partials_offset_calculation) {
  8741. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8742. ctx->do_add_rms_partials = false;
  8743. ctx->do_add_rms_partials_offset_calculation = false;
  8744. }
  8745. }
  8746. 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) {
  8747. float * op_params = (float *)dst->op_params;
  8748. 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 });
  8749. }
  8750. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8751. float * op_params = (float *)dst->op_params;
  8752. 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 });
  8753. }
  8754. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8755. 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 });
  8756. }
  8757. static void ggml_vk_xielu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8758. float * op_params = (float *)dst->op_params;
  8759. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY,
  8760. {
  8761. (uint32_t)ggml_nelements(src0), 0,
  8762. op_params[1], op_params[2], op_params[3], op_params[4]
  8763. }
  8764. );
  8765. }
  8766. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8767. const float * op_params_f = (const float *)dst->op_params;
  8768. const bool swapped = (bool)dst->op_params[1];
  8769. const bool split = src1 != nullptr;
  8770. const float alpha = op_params_f[2];
  8771. const float limit = op_params_f[3];
  8772. GGML_ASSERT(ggml_is_contiguous(src0));
  8773. if (!split) {
  8774. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8775. } else {
  8776. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8777. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8778. GGML_ASSERT(src0->type == src1->type);
  8779. }
  8780. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8781. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8782. {
  8783. (uint32_t)ggml_nelements(dst),
  8784. (uint32_t)src0->ne[0],
  8785. (uint32_t)dst->ne[0],
  8786. mode,
  8787. alpha,
  8788. limit
  8789. });
  8790. }
  8791. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8792. int32_t * op_params = (int32_t *)dst->op_params;
  8793. 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] });
  8794. }
  8795. 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) {
  8796. float * op_params = (float *)dst->op_params;
  8797. float scale = op_params[0];
  8798. float max_bias = op_params[1];
  8799. const uint32_t ncols = (uint32_t)src0->ne[0];
  8800. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8801. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8802. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8803. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8804. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8805. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8806. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8807. const uint32_t n_head_kv = src0->ne[2];
  8808. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8809. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8810. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8811. vk_op_soft_max_push_constants pc {
  8812. ncols,
  8813. src1 != nullptr ? nrows_y : (uint32_t)0,
  8814. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8815. ne12, ne13,
  8816. nb11, nb12, nb13,
  8817. scale, max_bias,
  8818. m0, m1,
  8819. n_head_log2,
  8820. nrows_x,
  8821. src2 != nullptr
  8822. };
  8823. if (ncols <= 16384) {
  8824. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, std::move(pc));
  8825. } else {
  8826. vk_subbuffer buf_a = ggml_vk_tensor_subbuffer(ctx, src0);
  8827. vk_subbuffer buf_b = src1 ? ggml_vk_tensor_subbuffer(ctx, src1) : buf_a;
  8828. vk_subbuffer buf_c = src2 ? ggml_vk_tensor_subbuffer(ctx, src2) : buf_a;
  8829. vk_subbuffer buf_d = ggml_vk_tensor_subbuffer(ctx, dst);
  8830. uint32_t elems_per_wg = 128 * 4;
  8831. uint32_t num_wgs = CEIL_DIV(ncols, elems_per_wg);
  8832. size_t tmp_size = num_wgs * nrows_x * sizeof(float);
  8833. if (ctx->prealloc_size_x < tmp_size) {
  8834. ctx->prealloc_size_x = tmp_size;
  8835. ggml_vk_preallocate_buffers(ctx, subctx);
  8836. }
  8837. if (ctx->prealloc_size_y < tmp_size) {
  8838. ctx->prealloc_size_y = tmp_size;
  8839. ggml_vk_preallocate_buffers(ctx, subctx);
  8840. }
  8841. if (ctx->prealloc_x_need_sync || ctx->prealloc_y_need_sync) {
  8842. ggml_vk_sync_buffers(ctx, subctx);
  8843. }
  8844. vk_subbuffer buf_x = { ctx->prealloc_x, 0, tmp_size };
  8845. vk_subbuffer buf_y = { ctx->prealloc_y, 0, tmp_size };
  8846. std::array<uint32_t, 3> elements = { num_wgs, nrows_x, 1 };
  8847. vk_pipeline pipeline1 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large1_f32_f16 : ctx->device->pipeline_soft_max_large1_f32;
  8848. vk_pipeline pipeline2 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large2_f32_f16 : ctx->device->pipeline_soft_max_large2_f32;
  8849. vk_pipeline pipeline3 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large3_f32_f16 : ctx->device->pipeline_soft_max_large3_f32;
  8850. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  8851. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  8852. ggml_pipeline_request_descriptor_sets(ctx, pipeline3, 1);
  8853. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8854. ggml_vk_sync_buffers(ctx, subctx);
  8855. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8856. ggml_vk_sync_buffers(ctx, subctx);
  8857. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline3, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8858. ctx->prealloc_x_need_sync = true;
  8859. ctx->prealloc_y_need_sync = true;
  8860. }
  8861. }
  8862. 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) {
  8863. float * op_params = (float *)dst->op_params;
  8864. 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 });
  8865. }
  8866. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8867. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8868. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8869. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8870. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8871. cgraph->nodes[node_idx + 5];
  8872. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8873. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8874. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8875. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8876. const int n_experts = logits->ne[0];
  8877. const int n_rows = logits->ne[1];
  8878. const int n_expert_used = weights->ne[1];
  8879. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8880. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8881. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8882. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  8883. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  8884. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  8885. vk_op_topk_moe_push_constants pc {};
  8886. pc.n_rows = n_rows;
  8887. pc.n_experts_push = n_experts;
  8888. pc.n_expert_used = n_expert_used;
  8889. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8890. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8891. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8892. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8893. }
  8894. GGML_ASSERT(n_expert_used <= n_experts);
  8895. const uint32_t rows_per_block = 4;
  8896. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8897. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, weights_buf, ids_buf}, pc, elements);
  8898. }
  8899. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  8900. ggml_tensor * dst = cgraph->nodes[node_idx];
  8901. const ggml_tensor * src0 = dst->src[0];
  8902. const ggml_tensor * src1 = dst->src[1];
  8903. const ggml_tensor * src2 = dst->src[2];
  8904. const ggml_tensor * src3 = nullptr;
  8905. const int n_dims = ((int32_t *) dst->op_params)[1];
  8906. const int mode = ((int32_t *) dst->op_params)[2];
  8907. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8908. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8909. const float freq_base = ((float *) dst->op_params)[5];
  8910. const float beta_fast = ((float *) dst->op_params)[9];
  8911. const float beta_slow = ((float *) dst->op_params)[10];
  8912. int sections[4] {};
  8913. if (mode & GGML_ROPE_TYPE_MROPE) {
  8914. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8915. }
  8916. float corr_dims[2];
  8917. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8918. uint32_t set_rows_stride = 0;
  8919. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8920. // and overrides the dst and sets src3=row_indices
  8921. if (ctx->num_additional_fused_ops > 0) {
  8922. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8923. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8924. dst = cgraph->nodes[node_idx + 2];
  8925. }
  8926. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  8927. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  8928. }
  8929. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8930. const uint32_t * op_params = (const uint32_t *)dst->op_params;
  8931. uint32_t ncols = src0->ne[0];
  8932. uint32_t nrows = ggml_nrows(src0);
  8933. uint32_t ncols_pad_log2 = (uint32_t)ceilf(log2f(float(ncols)));
  8934. uint32_t ncolsp2 = 1 << ncols_pad_log2;
  8935. vk_op_argsort_push_constants pc { ncols, ncolsp2, ncols_pad_log2, nrows, op_params[0], 0, 0, 0, 0, };
  8936. // Pick the largest workgroup size <= ncolsp2
  8937. uint32_t pipeline_idx = std::min(ncols_pad_log2, num_argsort_pipelines - 1);
  8938. // Use the "small" argsort shader if the whole sort can be done by a single workgroup.
  8939. bool use_small = ncols_pad_log2 <= ctx->device->max_workgroup_size_log2 &&
  8940. ctx->device->pipeline_argsort_f32[pipeline_idx] != nullptr;
  8941. vk_pipeline pipeline = use_small ? ctx->device->pipeline_argsort_f32[pipeline_idx]
  8942. : ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  8943. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  8944. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8945. vk_subbuffer subbuf1 = dst_buf;
  8946. // Reserve space for ivec2 per element, with rows padded to a power of two
  8947. if (!use_small) {
  8948. const size_t x_sz = size_t{ncolsp2} * nrows * 2 * sizeof(int);
  8949. if (ctx->prealloc_size_x < x_sz) {
  8950. ctx->prealloc_size_x = x_sz;
  8951. ggml_vk_preallocate_buffers(ctx, subctx);
  8952. }
  8953. if (ctx->prealloc_x_need_sync) {
  8954. ggml_vk_sync_buffers(ctx, subctx);
  8955. }
  8956. subbuf1 = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  8957. }
  8958. std::array<uint32_t, 3> elements;
  8959. elements[0] = ncolsp2;
  8960. elements[1] = std::min((uint32_t)ggml_nrows(src0), ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8961. elements[2] = 1;
  8962. // First dispatch initializes tmp_idx and does the first N passes where
  8963. // there is only communication between threads in the same workgroup.
  8964. {
  8965. vk_op_argsort_push_constants pc2 = pc;
  8966. pc2.outer_start = 0;
  8967. pc2.outer_end = std::min(ncols_pad_log2, ctx->device->max_workgroup_size_log2);
  8968. pc2.inner_start = 0;
  8969. pc2.inner_end = 100;
  8970. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8971. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  8972. }
  8973. if (!use_small) {
  8974. ggml_vk_sync_buffers(ctx, subctx);
  8975. // Loop over outer/inner passes, synchronizing between each pass.
  8976. for (uint32_t outer = ctx->device->max_workgroup_size_log2; outer < ncols_pad_log2; ++outer) {
  8977. for (uint32_t inner = 0; inner < outer + 1; ++inner) {
  8978. vk_op_argsort_push_constants pc2 = pc;
  8979. pc2.outer_start = outer;
  8980. pc2.outer_end = outer + 1;
  8981. pc2.inner_start = inner;
  8982. pc2.inner_end = inner + 1;
  8983. // When the inner idx is large enough, there's only communication
  8984. // within a workgroup. So the remaining inner iterations can all
  8985. // run in the same dispatch.
  8986. if (outer - inner < pipeline_idx) {
  8987. pc2.inner_end = 100;
  8988. inner = outer;
  8989. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  8990. } else {
  8991. // Smaller workgroup empirically seems to perform better
  8992. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx - 2];
  8993. }
  8994. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8995. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  8996. ggml_vk_sync_buffers(ctx, subctx);
  8997. }
  8998. }
  8999. ctx->prealloc_x_need_sync = true;
  9000. }
  9001. }
  9002. static void ggml_vk_topk(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9003. uint32_t ncols = src0->ne[0];
  9004. uint32_t nrows = ggml_nrows(src0);
  9005. uint32_t k = dst->ne[0];
  9006. vk_op_topk_push_constants pc { ncols, ncols, ncols, k, nrows, 0, 0 };
  9007. if (ctx->prealloc_x_need_sync) {
  9008. ggml_vk_sync_buffers(ctx, subctx);
  9009. }
  9010. std::array<uint32_t, 3> elements;
  9011. elements[1] = std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  9012. elements[2] = 1;
  9013. uint32_t num_elements = ncols;
  9014. // Each iteration reduces a workgroup's worth of elements down to the K
  9015. // largest elements. Repeat until we have the top K elements.
  9016. // Need to do at least one iteration to write out the results.
  9017. bool done_one_iter = false;
  9018. uint32_t dbl_buf_index = 0;
  9019. size_t dbl_buf_size;
  9020. while (num_elements > k || !done_one_iter) {
  9021. // Prefer going as small as num_topk_pipelines - 3 for perf reasons.
  9022. // But if K is larger, then we need a larger workgroup
  9023. uint32_t max_pipeline = num_topk_pipelines - 1;
  9024. uint32_t preferred_pipeline = std::max(num_topk_pipelines - 3, (uint32_t)log2f(float(k)) + 2);
  9025. max_pipeline = std::min(preferred_pipeline, max_pipeline);
  9026. uint32_t min_pipeline = (uint32_t)log2f(float(k)) + 1;
  9027. // require full subgroup
  9028. min_pipeline = std::max(min_pipeline, ctx->device->subgroup_size_log2);
  9029. uint32_t pipeline_idx = (uint32_t)ceilf(log2f(float(num_elements)));
  9030. pipeline_idx = std::min(pipeline_idx, max_pipeline);
  9031. pipeline_idx = std::max(pipeline_idx, min_pipeline);
  9032. if (num_elements > (1u << pipeline_idx)) {
  9033. // If we could finish on this loop iteration (i.e. a single workgroup)
  9034. // then do so. It's better than the overhead of another pass.
  9035. for (uint32_t i = pipeline_idx; i < num_topk_pipelines; ++i) {
  9036. if (num_elements <= (1u << i)) {
  9037. pipeline_idx = i;
  9038. break;
  9039. }
  9040. }
  9041. }
  9042. vk_pipeline pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  9043. // If the device doesn't support a pipeline this large, use smaller
  9044. while (!pipeline) {
  9045. pipeline_idx--;
  9046. GGML_ASSERT(pipeline_idx >= min_pipeline);
  9047. pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  9048. }
  9049. vk_op_topk_push_constants pc2 = pc;
  9050. pc2.ncols_input = num_elements;
  9051. // Number of elements remaining after this pass
  9052. uint32_t num_dst_elements = (num_elements / pipeline->wg_denoms[0]) * k + std::min(k, num_elements % pipeline->wg_denoms[0]);
  9053. pc2.ncols_output = num_dst_elements;
  9054. if (!done_one_iter) {
  9055. // Reserve space for ivec2 per element, double buffered
  9056. // K per workgroup per row
  9057. dbl_buf_size = num_dst_elements * nrows * 2 * sizeof(int);
  9058. dbl_buf_size = ROUNDUP_POW2(dbl_buf_size, ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  9059. const size_t x_sz = dbl_buf_size * 2;
  9060. if (ctx->prealloc_size_x < x_sz) {
  9061. ctx->prealloc_size_x = x_sz;
  9062. ggml_vk_preallocate_buffers(ctx, subctx);
  9063. }
  9064. }
  9065. vk_subbuffer src_buf;
  9066. vk_subbuffer dst_buf;
  9067. if (num_elements == ncols) {
  9068. pc2.first_pass = 1;
  9069. src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9070. } else {
  9071. src_buf = { ctx->prealloc_x, dbl_buf_index * dbl_buf_size, dbl_buf_size };
  9072. }
  9073. if (num_dst_elements == k) {
  9074. pc2.last_pass = 1;
  9075. dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9076. } else {
  9077. dst_buf = { ctx->prealloc_x, (dbl_buf_index ^ 1) * dbl_buf_size, dbl_buf_size };
  9078. }
  9079. elements[0] = num_elements;
  9080. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9081. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src_buf, dst_buf }, pc2, elements);
  9082. num_elements = num_dst_elements;
  9083. dbl_buf_index ^= 1;
  9084. if (num_elements > k) {
  9085. ggml_vk_sync_buffers(ctx, subctx);
  9086. }
  9087. done_one_iter = true;
  9088. }
  9089. ctx->prealloc_x_need_sync = true;
  9090. }
  9091. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9092. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  9093. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  9094. }
  9095. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9096. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9097. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  9098. }
  9099. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9100. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9101. p.weight = 1.0f / (float)src0->ne[0];
  9102. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  9103. }
  9104. static void ggml_vk_cumsum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9105. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9106. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CUMSUM, p);
  9107. }
  9108. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9109. 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 });
  9110. }
  9111. 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) {
  9112. 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 });
  9113. }
  9114. 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) {
  9115. const uint32_t src0_type_size = ggml_type_size(src0->type);
  9116. const uint32_t src1_type_size = ggml_type_size(src1->type);
  9117. const uint32_t dst_type_size = ggml_type_size(dst->type);
  9118. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOLVE_TRI, {
  9119. (uint32_t)ggml_nelements(src0),
  9120. (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,
  9121. (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,
  9122. (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,
  9123. 0,
  9124. 0.0f, 0.0f, 0,
  9125. });
  9126. }
  9127. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9128. const int32_t s0 = dst->op_params[0];
  9129. const int32_t s1 = dst->op_params[1];
  9130. const int32_t p0 = dst->op_params[2];
  9131. const int32_t p1 = dst->op_params[3];
  9132. const int32_t d0 = dst->op_params[4];
  9133. const int32_t d1 = dst->op_params[5];
  9134. const bool is_2D = dst->op_params[6] == 1;
  9135. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  9136. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  9137. const uint32_t IW = src1->ne[0];
  9138. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  9139. const uint32_t KW = src0->ne[0];
  9140. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  9141. const uint32_t OW = dst->ne[1];
  9142. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  9143. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  9144. const uint32_t pelements = OW * KW * KH;
  9145. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  9146. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9147. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9148. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9149. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  9150. dst_addr,
  9151. batch_offset, offset_delta,
  9152. IC, IW, IH, OW, OH, KW, KH,
  9153. pelements,
  9154. IC * KH * KW,
  9155. s0, s1, p0, p1, d0, d1, batch * IC
  9156. });
  9157. }
  9158. 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) {
  9159. GGML_TENSOR_BINARY_OP_LOCALS
  9160. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  9161. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  9162. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  9163. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  9164. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  9165. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  9166. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  9167. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  9168. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  9169. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  9170. const int64_t N = ne13 / IC;
  9171. const int64_t ID = ne12;
  9172. const int64_t IH = ne11;
  9173. const int64_t IW = ne10;
  9174. const int64_t KD = ne02;
  9175. const int64_t KH = ne01;
  9176. const int64_t KW = ne00;
  9177. const int64_t OD = ne3 / N;
  9178. const int64_t OH = ne2;
  9179. const int64_t OW = ne1;
  9180. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9181. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9182. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9183. vk_op_im2col_3d_push_constants pc {};
  9184. pc.dst_addr = dst_addr;
  9185. pc.nb10 = nb10 / ggml_type_size(src1->type);
  9186. pc.nb11 = nb11 / ggml_type_size(src1->type);
  9187. pc.nb12 = nb12 / ggml_type_size(src1->type);
  9188. pc.nb13 = nb13 / ggml_type_size(src1->type);
  9189. pc.s0 = s0;
  9190. pc.s1 = s1;
  9191. pc.s2 = s2;
  9192. pc.p0 = p0;
  9193. pc.p1 = p1;
  9194. pc.p2 = p2;
  9195. pc.d0 = d0;
  9196. pc.d1 = d1;
  9197. pc.d2 = d2;
  9198. pc.IW = IW;
  9199. pc.IH = IH;
  9200. pc.ID = ID;
  9201. pc.IC = IC;
  9202. pc.KW = KW;
  9203. pc.OH = OH;
  9204. pc.KD_KH_KW = KD*KH*KW;
  9205. pc.KH_KW = KH*KW;
  9206. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  9207. pc.N_OD_OH = N*OD*OH;
  9208. pc.OD_OH = OD*OH;
  9209. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  9210. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  9211. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  9212. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  9213. }
  9214. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9215. const uint32_t dim = dst->op_params[0];
  9216. const uint32_t max_period = dst->op_params[1];
  9217. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  9218. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  9219. nb1, dim, max_period,
  9220. });
  9221. }
  9222. 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) {
  9223. // src0: (K, Cout, Cin, 1) -- kernel
  9224. // src1: (L, Cin, 1, 1) -- input
  9225. // dst: (*, Cout, 1, 1)
  9226. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  9227. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9228. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  9229. GGML_TENSOR_BINARY_OP_LOCALS
  9230. GGML_ASSERT(nb00 == sizeof(float));
  9231. GGML_ASSERT(nb10 == sizeof(float));
  9232. const int32_t s0 = dst->op_params[0];
  9233. vk_op_conv_transpose_1d_push_constants p{};
  9234. p.Cout = static_cast<uint32_t>(ne01);
  9235. p.Cin = static_cast<uint32_t>(ne02);
  9236. p.K = static_cast<uint32_t>(ne00);
  9237. p.L = static_cast<uint32_t>(ne10);
  9238. p.KL = static_cast<uint32_t>(ne0);
  9239. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9240. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9241. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9242. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9243. p.s0 = static_cast<uint32_t>(s0);
  9244. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  9245. }
  9246. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9247. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  9248. const int32_t k1 = dst->op_params[1];
  9249. const int32_t k0 = dst->op_params[2];
  9250. const int32_t s1 = dst->op_params[3];
  9251. const int32_t s0 = dst->op_params[4];
  9252. const int32_t p1 = dst->op_params[5];
  9253. const int32_t p0 = dst->op_params[6];
  9254. const uint32_t IH = src0->ne[1];
  9255. const uint32_t IW = src0->ne[0];
  9256. const uint32_t N = dst->ne[3];
  9257. const uint32_t OC = dst->ne[2];
  9258. const uint32_t OH = dst->ne[1];
  9259. const uint32_t OW = dst->ne[0];
  9260. const uint32_t parallel_elements = N * OC * OH * OW;
  9261. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  9262. IW, IH, OW, OH, OC,
  9263. parallel_elements,
  9264. op,
  9265. k0, k1, s0, s1, p0, p1,
  9266. });
  9267. }
  9268. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  9269. const ggml_tensor * src1, ggml_tensor * dst) {
  9270. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  9271. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9272. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  9273. GGML_TENSOR_BINARY_OP_LOCALS
  9274. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  9275. GGML_ASSERT(nb10 == sizeof(float));
  9276. GGML_ASSERT(nb0 == sizeof(float));
  9277. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  9278. vk_op_conv2d_push_constants p{};
  9279. p.Cout = static_cast<uint32_t>(!transpose ? ne03 : ne02);
  9280. p.Cin = static_cast<uint32_t>(!transpose ? ne02 : ne03);
  9281. p.N = static_cast<uint32_t>(ne13);
  9282. GGML_ASSERT(p.Cout == ne2);
  9283. GGML_ASSERT(p.Cin == ne12);
  9284. p.W = static_cast<uint32_t>(ne10);
  9285. p.H = static_cast<uint32_t>(ne11);
  9286. p.OW = static_cast<uint32_t>(ne0);
  9287. p.OH = static_cast<uint32_t>(ne1);
  9288. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9289. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9290. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  9291. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9292. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  9293. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  9294. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9295. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  9296. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  9297. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, dst->op, std::move(p));
  9298. }
  9299. 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) {
  9300. vk_op_conv2d_dw_push_constants p{};
  9301. p.ne = ggml_nelements(dst);
  9302. p.channels = dst->ne[2];
  9303. p.batches = dst->ne[3];
  9304. p.dst_w = dst->ne[0];
  9305. p.dst_h = dst->ne[1];
  9306. p.src_w = src1->ne[0];
  9307. p.src_h = src1->ne[1];
  9308. p.knl_w = src0->ne[0];
  9309. p.knl_h = src0->ne[1];
  9310. p.stride_x = dst->op_params[0];
  9311. p.stride_y = dst->op_params[1];
  9312. p.pad_x = dst->op_params[2];
  9313. p.pad_y = dst->op_params[3];
  9314. p.dilation_x = dst->op_params[4];
  9315. p.dilation_y = dst->op_params[5];
  9316. GGML_ASSERT(src0->ne[3] == p.channels);
  9317. GGML_ASSERT(src1->ne[3] == p.batches);
  9318. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  9319. }
  9320. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9321. const float * op_params = (const float *)dst->op_params;
  9322. 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 });
  9323. }
  9324. #ifdef GGML_VULKAN_RUN_TESTS
  9325. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  9326. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  9327. return;
  9328. }
  9329. i0 = std::max(i0, 5);
  9330. i1 = std::max(i1, 5);
  9331. i2 = std::max(i2, 0);
  9332. fprintf(stderr, " ");
  9333. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9334. fprintf(stderr, "%7d ", idx1);
  9335. }
  9336. fprintf(stderr, "\n");
  9337. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9338. fprintf(stderr, "%7d: ", idx0);
  9339. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9340. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  9341. float val;
  9342. if (type == GGML_TYPE_F32) {
  9343. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  9344. } else if (type == GGML_TYPE_F16) {
  9345. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  9346. } else {
  9347. GGML_ABORT("fatal error");
  9348. }
  9349. fprintf(stderr, "% 7.2f ", val);
  9350. } else {
  9351. fprintf(stderr, " ");
  9352. }
  9353. }
  9354. fprintf(stderr, "\n");
  9355. }
  9356. }
  9357. template <typename X_TYPE, typename Y_TYPE>
  9358. 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) {
  9359. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  9360. const size_t x_ne = m * k * batch;
  9361. const size_t y_ne = k * n * batch;
  9362. const size_t d_ne = m * n * batch;
  9363. vk_pipeline p;
  9364. std::string shname;
  9365. if (shader_size == 0) {
  9366. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9367. p = ctx->device->pipeline_matmul_f32->a_s;
  9368. shname = "F32_ALIGNED_S";
  9369. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9370. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  9371. shname = "F32_F16_ALIGNED_S";
  9372. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9373. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  9374. shname = "F16_F32_ALIGNED_S";
  9375. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9376. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  9377. shname = "F16_ALIGNED_S";
  9378. } else {
  9379. GGML_ABORT("fatal error");
  9380. }
  9381. } else if (shader_size == 1) {
  9382. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9383. p = ctx->device->pipeline_matmul_f32->a_m;
  9384. shname = "F32_ALIGNED_M";
  9385. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9386. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  9387. shname = "F32_F16_ALIGNED_M";
  9388. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9389. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  9390. shname = "F16_F32_ALIGNED_M";
  9391. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9392. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  9393. shname = "F16_ALIGNED_M";
  9394. } else {
  9395. GGML_ABORT("fatal error");
  9396. }
  9397. } else if (shader_size == 2) {
  9398. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9399. p = ctx->device->pipeline_matmul_f32->a_l;
  9400. shname = "F32_ALIGNED_L";
  9401. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9402. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  9403. shname = "F32_F16_ALIGNED_L";
  9404. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9405. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  9406. shname = "F16_F32_ALIGNED_L";
  9407. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9408. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  9409. shname = "F16_ALIGNED_L";
  9410. } else {
  9411. GGML_ABORT("fatal error");
  9412. }
  9413. } else {
  9414. GGML_ASSERT(0);
  9415. }
  9416. const size_t kpad = ggml_vk_align_size(k, p->align);
  9417. if (k != kpad) {
  9418. if (shader_size == 0) {
  9419. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9420. p = ctx->device->pipeline_matmul_f32->s;
  9421. shname = "F32_S";
  9422. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9423. p = ctx->device->pipeline_matmul_f32_f16->s;
  9424. shname = "F32_F16_S";
  9425. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9426. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  9427. shname = "F16_F32_S";
  9428. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9429. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  9430. shname = "F16_S";
  9431. }
  9432. } else if (shader_size == 1) {
  9433. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9434. p = ctx->device->pipeline_matmul_f32->m;
  9435. shname = "F32_M";
  9436. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9437. p = ctx->device->pipeline_matmul_f32_f16->m;
  9438. shname = "F32_F16_M";
  9439. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9440. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  9441. shname = "F16_F32_M";
  9442. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9443. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  9444. shname = "F16_M";
  9445. }
  9446. } else if (shader_size == 2) {
  9447. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9448. p = ctx->device->pipeline_matmul_f32->l;
  9449. shname = "F32_L";
  9450. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9451. p = ctx->device->pipeline_matmul_f32_f16->l;
  9452. shname = "F32_F16_L";
  9453. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9454. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  9455. shname = "F16_F32_L";
  9456. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9457. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  9458. shname = "F16_L";
  9459. }
  9460. }
  9461. }
  9462. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9463. if (split_k > 1) {
  9464. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9465. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9466. // Resize buffer
  9467. if (ctx->prealloc_split_k != nullptr) {
  9468. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9469. }
  9470. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9471. }
  9472. }
  9473. ggml_pipeline_allocate_descriptor_sets(ctx);
  9474. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9475. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9476. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9477. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9478. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9479. float* d = (float *) malloc(sizeof(float) * d_ne);
  9480. for (size_t i = 0; i < x_ne; i++) {
  9481. if (std::is_same<float, X_TYPE>()) {
  9482. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9483. // x[i] = 1.0f;
  9484. // x[i] = i + 1;
  9485. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9486. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9487. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9488. // x[i] = ggml_fp32_to_fp16(1.0f);
  9489. // x[i] = ggml_fp32_to_fp16(i + 1);
  9490. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9491. } else {
  9492. GGML_ABORT("fatal error");
  9493. }
  9494. }
  9495. for (size_t i = 0; i < y_ne; i++) {
  9496. if (std::is_same<float, Y_TYPE>()) {
  9497. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9498. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9499. // y[i] = i + 1;
  9500. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9501. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9502. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9503. // y[i] = ggml_fp32_to_fp16(i + 1);
  9504. } else {
  9505. GGML_ABORT("fatal error");
  9506. }
  9507. }
  9508. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9509. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9510. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9511. ggml_vk_ctx_begin(ctx->device, subctx);
  9512. for (size_t i = 0; i < num_it; i++) {
  9513. ggml_vk_matmul(
  9514. 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),
  9515. m, n, k,
  9516. k, k, m, k*m, k*n, m*n,
  9517. split_k, batch, batch, batch, 1, 1, n
  9518. );
  9519. }
  9520. ggml_vk_ctx_end(subctx);
  9521. auto begin = std::chrono::high_resolution_clock::now();
  9522. ggml_vk_submit(subctx, ctx->fence);
  9523. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9524. ctx->device->device.resetFences({ ctx->fence });
  9525. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9526. auto end = std::chrono::high_resolution_clock::now();
  9527. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9528. // copy dst to host
  9529. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9530. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9531. ggml_init_params iparams = {
  9532. /*.mem_size =*/ 1024*1024*1024,
  9533. /*.mem_buffer =*/ NULL,
  9534. /*.no_alloc =*/ true,
  9535. };
  9536. ggml_context * ggml_ctx = ggml_init(iparams);
  9537. ggml_type src0_type;
  9538. ggml_type src1_type;
  9539. if (std::is_same<float, X_TYPE>()) {
  9540. src0_type = GGML_TYPE_F32;
  9541. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9542. src0_type = GGML_TYPE_F16;
  9543. } else {
  9544. GGML_ABORT("fatal error");
  9545. }
  9546. if (std::is_same<float, Y_TYPE>()) {
  9547. src1_type = GGML_TYPE_F32;
  9548. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9549. src1_type = GGML_TYPE_F16;
  9550. } else {
  9551. GGML_ABORT("fatal error");
  9552. }
  9553. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9554. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9555. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9556. src0_ggml->data = x;
  9557. src1_ggml->data = y;
  9558. tensor_ggml->data = d_chk;
  9559. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9560. ggml_build_forward_expand(cgraph, tensor_ggml);
  9561. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9562. ggml_free(ggml_ctx);
  9563. double avg_err = 0.0;
  9564. int first_err_n = -1;
  9565. int first_err_m = -1;
  9566. int first_err_b = -1;
  9567. for (size_t i = 0; i < m*n*batch; i++) {
  9568. double err = std::fabs(d[i] - d_chk[i]);
  9569. avg_err += err;
  9570. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9571. first_err_b = i / (m * n);
  9572. first_err_n = (i % (m * n)) / m;
  9573. first_err_m = (i % (m * n)) % m;
  9574. }
  9575. }
  9576. avg_err /= m * n;
  9577. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9578. 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;
  9579. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9580. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9581. std::cerr << "Actual result: " << std::endl << std::endl;
  9582. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9583. std::cerr << "Expected result: " << std::endl << std::endl;
  9584. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9585. if (split_k > 1) {
  9586. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9587. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9588. std::cerr << "d_buf0: " << std::endl << std::endl;
  9589. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9590. std::cerr << "d_buf1: " << std::endl << std::endl;
  9591. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9592. std::cerr << "d_buf2: " << std::endl << std::endl;
  9593. 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);
  9594. std::cerr << "d_buf3: " << std::endl << std::endl;
  9595. 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);
  9596. free(split_k_buf);
  9597. }
  9598. }
  9599. free(d_chk);
  9600. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9601. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9602. ggml_vk_destroy_buffer(d_X);
  9603. ggml_vk_destroy_buffer(d_Y);
  9604. ggml_vk_destroy_buffer(d_D);
  9605. free(x);
  9606. free(y);
  9607. free(d);
  9608. }
  9609. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9610. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9611. return;
  9612. }
  9613. i0 = std::max(i0, 5);
  9614. i1 = std::max(i1, 5);
  9615. i2 = std::max(i2, 0);
  9616. i3 = std::max(i3, 0);
  9617. fprintf(stderr, " ");
  9618. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9619. fprintf(stderr, "%7d ", idx1);
  9620. }
  9621. fprintf(stderr, "\n");
  9622. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9623. fprintf(stderr, "%7d: ", idx0);
  9624. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9625. 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]) {
  9626. float val;
  9627. if (tensor->type == GGML_TYPE_F32) {
  9628. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9629. } else if (tensor->type == GGML_TYPE_F16) {
  9630. 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]));
  9631. } else {
  9632. GGML_ABORT("fatal error");
  9633. }
  9634. fprintf(stderr, "% 7.2f ", val);
  9635. } else {
  9636. fprintf(stderr, " ");
  9637. }
  9638. }
  9639. fprintf(stderr, "\n");
  9640. }
  9641. }
  9642. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9643. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9644. }
  9645. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9646. if (quant == GGML_TYPE_F32) {
  9647. memcpy(to, from, sizeof(float) * ne);
  9648. return;
  9649. }
  9650. const auto * tt = ggml_get_type_traits(quant);
  9651. ggml_to_float_t dequant_fn = tt->to_float;
  9652. dequant_fn(from, to, ne);
  9653. }
  9654. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9655. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9656. const size_t x_sz = sizeof(float) * ne;
  9657. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9658. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9659. float * x = (float *) malloc(x_sz);
  9660. void * qx = malloc(qx_sz);
  9661. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9662. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9663. float * x_ref = (float *) malloc(x_sz);
  9664. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9665. for (size_t i = 0; i < ne; i++) {
  9666. x[i] = rand() / (float)RAND_MAX;
  9667. }
  9668. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9669. ggml_vk_quantize_data(x, qx, ne, quant);
  9670. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9671. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9672. ggml_pipeline_allocate_descriptor_sets(ctx);
  9673. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9674. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9675. ggml_vk_ctx_begin(ctx->device, subctx);
  9676. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9677. 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});
  9678. ggml_vk_ctx_end(subctx);
  9679. auto begin = std::chrono::high_resolution_clock::now();
  9680. ggml_vk_submit(subctx, ctx->fence);
  9681. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9682. ctx->device->device.resetFences({ ctx->fence });
  9683. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9684. auto end = std::chrono::high_resolution_clock::now();
  9685. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9686. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9687. int first_err = -1;
  9688. double avg_err = 0.0;
  9689. for (size_t i = 0; i < ne; i++) {
  9690. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9691. avg_err += error;
  9692. if (first_err < 0 && error > 0.05) {
  9693. first_err = i;
  9694. }
  9695. }
  9696. avg_err /= ne;
  9697. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9698. if (avg_err > 0.1) {
  9699. std::cerr << "first_error = " << first_err << std::endl;
  9700. std::cerr << "Actual result: " << std::endl << std::endl;
  9701. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9702. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9703. }
  9704. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9705. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9706. std::cerr << x_ref[i] << ", ";
  9707. }
  9708. std::cerr << std::endl;
  9709. }
  9710. ggml_vk_destroy_buffer(x_buf);
  9711. ggml_vk_destroy_buffer(qx_buf);
  9712. free(x);
  9713. free(qx);
  9714. free(x_ref);
  9715. free(x_chk);
  9716. }
  9717. // This does not work without ggml q8_1 quantization support
  9718. //
  9719. // typedef uint16_t ggml_half;
  9720. // typedef uint32_t ggml_half2;
  9721. //
  9722. // #define QK8_1 32
  9723. // typedef struct {
  9724. // union {
  9725. // struct {
  9726. // ggml_half d; // delta
  9727. // ggml_half s; // d * sum(qs[i])
  9728. // } GGML_COMMON_AGGR_S;
  9729. // ggml_half2 ds;
  9730. // } GGML_COMMON_AGGR_U;
  9731. // int8_t qs[QK8_1]; // quants
  9732. // } block_q8_1;
  9733. //
  9734. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9735. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9736. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9737. //
  9738. // const size_t x_sz = sizeof(float) * ne;
  9739. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9740. // float * x = (float *) malloc(x_sz);
  9741. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9742. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9743. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9744. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9745. //
  9746. // for (size_t i = 0; i < ne; i++) {
  9747. // x[i] = rand() / (float)RAND_MAX;
  9748. // }
  9749. //
  9750. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9751. //
  9752. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9753. //
  9754. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9755. //
  9756. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9757. //
  9758. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9759. // ggml_vk_ctx_begin(ctx->device, subctx);
  9760. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9761. // ggml_vk_ctx_end(subctx);
  9762. //
  9763. // auto begin = std::chrono::high_resolution_clock::now();
  9764. //
  9765. // ggml_vk_submit(subctx, ctx->fence);
  9766. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9767. // ctx->device->device.resetFences({ ctx->fence });
  9768. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9769. //
  9770. // auto end = std::chrono::high_resolution_clock::now();
  9771. //
  9772. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9773. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9774. //
  9775. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9776. //
  9777. // int first_err = -1;
  9778. //
  9779. // for (size_t i = 0; i < ne / 32; i++) {
  9780. // 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));
  9781. //
  9782. // if (first_err < 0 && error > 0.1) {
  9783. // first_err = i;
  9784. // }
  9785. //
  9786. // 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));
  9787. //
  9788. // if (first_err < 0 && error > 0.1) {
  9789. // first_err = i;
  9790. // }
  9791. //
  9792. // for (size_t j = 0; j < 32; j++) {
  9793. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9794. //
  9795. // if (first_err < 0 && error > 1) {
  9796. // first_err = i;
  9797. // }
  9798. // }
  9799. // }
  9800. //
  9801. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9802. //
  9803. // if (first_err != -1) {
  9804. // std::cerr << "first_error = " << first_err << std::endl;
  9805. // std::cerr << "Actual result: " << std::endl << std::endl;
  9806. // 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) << " ";
  9807. // for (size_t j = 0; j < 32; j++) {
  9808. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9809. // }
  9810. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9811. // 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) << " ";
  9812. // for (size_t j = 0; j < 32; j++) {
  9813. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9814. // }
  9815. // std::cerr << std::endl;
  9816. // }
  9817. //
  9818. // ggml_vk_destroy_buffer(x_buf);
  9819. // ggml_vk_destroy_buffer(qx_buf);
  9820. //
  9821. // free(x);
  9822. // free(qx);
  9823. // free(qx_res);
  9824. // }
  9825. 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) {
  9826. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9827. const size_t x_ne = m * k * batch;
  9828. const size_t y_ne = k * n * batch;
  9829. const size_t d_ne = m * n * batch;
  9830. vk_matmul_pipeline2 * pipelines;
  9831. if (mmq) {
  9832. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9833. } else {
  9834. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9835. }
  9836. const bool fp16acc = ctx->device->fp16;
  9837. vk_pipeline p;
  9838. std::string shname;
  9839. if (shader_size == 0) {
  9840. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9841. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9842. } else if (shader_size == 1) {
  9843. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9844. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9845. } else if (shader_size == 2) {
  9846. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9847. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9848. } else {
  9849. GGML_ASSERT(0);
  9850. }
  9851. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9852. if (mmq || k != kpad) {
  9853. if (shader_size == 0) {
  9854. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9855. shname = std::string(ggml_type_name(quant)) + "_S";
  9856. } else if (shader_size == 1) {
  9857. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9858. shname = std::string(ggml_type_name(quant)) + "_M";
  9859. } else if (shader_size == 2) {
  9860. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9861. shname = std::string(ggml_type_name(quant)) + "_L";
  9862. } else {
  9863. GGML_ASSERT(0);
  9864. }
  9865. }
  9866. if (p == nullptr) {
  9867. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9868. return;
  9869. }
  9870. const size_t x_sz = sizeof(float) * x_ne;
  9871. const size_t y_sz = sizeof(float) * y_ne;
  9872. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9873. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9874. const size_t d_sz = sizeof(float) * d_ne;
  9875. float * x = (float *) malloc(x_sz);
  9876. float * y = (float *) malloc(y_sz);
  9877. void * qx = malloc(qx_sz);
  9878. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9879. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9880. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9881. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9882. float * d = (float *) malloc(d_sz);
  9883. float * d_chk = (float *) malloc(d_sz);
  9884. for (size_t i = 0; i < x_ne; i++) {
  9885. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9886. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9887. // x[i] = i % k;
  9888. }
  9889. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9890. for (size_t i = 0; i < y_ne; i++) {
  9891. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9892. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9893. // y[i] = i % k;
  9894. }
  9895. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9896. if (split_k > 1) {
  9897. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9898. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9899. // Resize buffer
  9900. if (ctx->prealloc_split_k != nullptr) {
  9901. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9902. }
  9903. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9904. }
  9905. }
  9906. if (mmq) {
  9907. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9908. }
  9909. ggml_pipeline_allocate_descriptor_sets(ctx);
  9910. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9911. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9912. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9913. ggml_vk_ctx_begin(ctx->device, subctx);
  9914. if (mmq) {
  9915. for (size_t i = 0; i < num_it; i++) {
  9916. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9917. ggml_vk_matmul(
  9918. 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 },
  9919. m, n, k,
  9920. k, k, m, k*m, k*n, m*n,
  9921. split_k, batch, batch, batch, 1, 1, n
  9922. );
  9923. }
  9924. } else {
  9925. for (size_t i = 0; i < num_it; i++) {
  9926. ggml_vk_matmul(
  9927. 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 },
  9928. m, n, k,
  9929. k, k, m, k*m, k*n, m*n,
  9930. split_k, batch, batch, batch, 1, 1, n
  9931. );
  9932. }
  9933. }
  9934. ggml_vk_ctx_end(subctx);
  9935. auto begin = std::chrono::high_resolution_clock::now();
  9936. ggml_vk_submit(subctx, ctx->fence);
  9937. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9938. ctx->device->device.resetFences({ ctx->fence });
  9939. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9940. auto end = std::chrono::high_resolution_clock::now();
  9941. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9942. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9943. ggml_init_params iparams = {
  9944. /*.mem_size =*/ 1024*1024*1024,
  9945. /*.mem_buffer =*/ NULL,
  9946. /*.no_alloc =*/ true,
  9947. };
  9948. ggml_context * ggml_ctx = ggml_init(iparams);
  9949. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9950. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9951. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9952. src0_ggml->data = qx;
  9953. src1_ggml->data = y;
  9954. tensor_ggml->data = d_chk;
  9955. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9956. ggml_build_forward_expand(cgraph, tensor_ggml);
  9957. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9958. ggml_free(ggml_ctx);
  9959. double avg_err = 0.0;
  9960. int first_err_n = -1;
  9961. int first_err_m = -1;
  9962. int first_err_b = -1;
  9963. for (size_t i = 0; i < m*n*batch; i++) {
  9964. double err = std::fabs(d[i] - d_chk[i]);
  9965. avg_err += err;
  9966. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9967. first_err_b = i / (m * n);
  9968. first_err_n = (i % (m * n)) / m;
  9969. first_err_m = (i % (m * n)) % m;
  9970. }
  9971. }
  9972. avg_err /= m * n;
  9973. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9974. std::cerr << "TEST dequant matmul " << shname;
  9975. if (mmq) {
  9976. std::cerr << " mmq";
  9977. }
  9978. 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;
  9979. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9980. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9981. std::cerr << "Actual result: " << std::endl << std::endl;
  9982. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9983. std::cerr << std::endl;
  9984. std::cerr << "Expected result: " << std::endl << std::endl;
  9985. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9986. std::cerr << "src0: " << std::endl << std::endl;
  9987. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9988. std::cerr << std::endl;
  9989. std::cerr << "src1: " << std::endl << std::endl;
  9990. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9991. if (split_k > 1) {
  9992. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9993. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9994. std::cerr << "d_buf0: " << std::endl << std::endl;
  9995. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9996. std::cerr << "d_buf1: " << std::endl << std::endl;
  9997. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9998. std::cerr << "d_buf2: " << std::endl << std::endl;
  9999. 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);
  10000. std::cerr << "d_buf3: " << std::endl << std::endl;
  10001. 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);
  10002. free(split_k_buf);
  10003. }
  10004. }
  10005. ggml_vk_destroy_buffer(qx_buf);
  10006. ggml_vk_destroy_buffer(y_buf);
  10007. ggml_vk_destroy_buffer(qy_buf);
  10008. ggml_vk_destroy_buffer(d_buf);
  10009. free(x);
  10010. free(qx);
  10011. free(y);
  10012. free(d);
  10013. free(d_chk);
  10014. }
  10015. #endif
  10016. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  10017. #if defined(GGML_VULKAN_RUN_TESTS)
  10018. const std::vector<size_t> vals {
  10019. 512, 512, 128,
  10020. 128, 512, 512,
  10021. 4096, 512, 4096,
  10022. 11008, 512, 4096,
  10023. 4096, 512, 11008,
  10024. 32000, 512, 4096,
  10025. 8, 8, 8,
  10026. 100, 46, 576,
  10027. 623, 111, 128,
  10028. 100, 46, 558,
  10029. 512, 1, 256,
  10030. 128, 110, 622,
  10031. 511, 511, 127,
  10032. 511, 511, 7,
  10033. 511, 511, 17,
  10034. 49, 49, 128,
  10035. 128, 49, 49,
  10036. 4096, 49, 4096,
  10037. };
  10038. const size_t num_it = 100;
  10039. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  10040. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  10041. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  10042. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  10043. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  10044. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  10045. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  10046. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  10047. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  10048. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  10049. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  10050. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  10051. abort();
  10052. for (size_t i = 0; i < vals.size(); i += 3) {
  10053. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  10054. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  10055. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  10056. std::cerr << '\n';
  10057. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  10058. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  10059. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  10060. std::cerr << '\n';
  10061. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  10062. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  10063. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  10064. std::cerr << '\n' << std::endl;
  10065. if (vals[i + 2] % 32 == 0) {
  10066. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  10067. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  10068. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  10069. std::cerr << '\n';
  10070. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  10071. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  10072. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  10073. std::cerr << '\n';
  10074. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  10075. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  10076. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  10077. std::cerr << '\n' << std::endl;
  10078. }
  10079. if (vals[i + 2] % 256 == 0) {
  10080. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  10081. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  10082. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  10083. std::cerr << '\n';
  10084. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  10085. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  10086. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  10087. std::cerr << '\n';
  10088. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  10089. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  10090. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  10091. std::cerr << '\n' << std::endl;
  10092. }
  10093. }
  10094. GGML_ABORT("fatal error");
  10095. #endif
  10096. if (subctx) {
  10097. // Submit and wait for any pending work before reallocating the buffers
  10098. ggml_vk_ctx_end(subctx);
  10099. ggml_vk_submit(subctx, {});
  10100. ctx->submit_pending = true;
  10101. ggml_vk_synchronize(ctx);
  10102. ggml_vk_ctx_begin(ctx->device, subctx);
  10103. }
  10104. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  10105. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  10106. // Resize buffer
  10107. if (ctx->prealloc_x != nullptr) {
  10108. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10109. }
  10110. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  10111. }
  10112. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  10113. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  10114. // Resize buffer
  10115. if (ctx->prealloc_y != nullptr) {
  10116. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10117. }
  10118. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  10119. }
  10120. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  10121. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  10122. // Resize buffer
  10123. if (ctx->prealloc_split_k != nullptr) {
  10124. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10125. }
  10126. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  10127. }
  10128. 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)) {
  10129. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  10130. // Resize buffer
  10131. if (ctx->prealloc_add_rms_partials != nullptr) {
  10132. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10133. }
  10134. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  10135. }
  10136. }
  10137. static void ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool almost_ready);
  10138. // Returns true if node has enqueued work into the queue, false otherwise
  10139. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  10140. 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){
  10141. ggml_tensor * node = cgraph->nodes[node_idx];
  10142. if (ggml_is_empty(node) || ggml_op_is_empty(node->op) || !node->buffer) {
  10143. return false;
  10144. }
  10145. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  10146. ctx->semaphore_idx = 0;
  10147. ggml_tensor * src0 = node->src[0];
  10148. ggml_tensor * src1 = node->src[1];
  10149. ggml_tensor * src2 = node->src[2];
  10150. ggml_tensor * src3 = node->src[3];
  10151. if (node->op == GGML_OP_ADD) {
  10152. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  10153. if (next_node_idx < cgraph->n_nodes &&
  10154. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  10155. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  10156. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  10157. ctx->device->add_rms_fusion) {
  10158. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  10159. ctx->do_add_rms_partials_offset_calculation = true;
  10160. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  10161. ctx->do_add_rms_partials = true;
  10162. }
  10163. }
  10164. }
  10165. vk_context compute_ctx;
  10166. if (ctx->compute_ctx.expired()) {
  10167. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10168. ctx->compute_ctx = compute_ctx;
  10169. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10170. } else {
  10171. compute_ctx = ctx->compute_ctx.lock();
  10172. }
  10173. {
  10174. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  10175. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  10176. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  10177. // outside of this logic. When a node uses one of the prealloc buffers for something like
  10178. // dequantization or split_k, additional synchronization is needed between those passes.
  10179. bool need_sync = false;
  10180. // Check whether "node" requires synchronization. The node requires synchronization if it
  10181. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  10182. // Destination nodes are checked against both the written/read lists. Source nodes are only
  10183. // checked against the written list. Two nodes overlap in memory if they come from the same
  10184. // buffer and the tensor or view ranges overlap.
  10185. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  10186. if (unsynced_nodes.size() == 0) {
  10187. return false;
  10188. }
  10189. auto n_base = vk_tensor_offset(node) + node->view_offs;
  10190. auto n_size = ggml_nbytes(node);
  10191. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  10192. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10193. for (auto &other : unsynced_nodes) {
  10194. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  10195. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  10196. if (a_buf == o_buf) {
  10197. auto o_base = vk_tensor_offset(other) + other->view_offs;
  10198. auto o_size = ggml_nbytes(other);
  10199. if ((o_base <= n_base && n_base < o_base + o_size) ||
  10200. (n_base <= o_base && o_base < n_base + n_size)) {
  10201. return true;
  10202. }
  10203. }
  10204. }
  10205. return false;
  10206. };
  10207. // For all fused ops, check if the destination node or any of the source
  10208. // nodes require synchronization.
  10209. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  10210. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10211. // If the node actually writes to memory, then check if it needs to sync
  10212. if (ctx->fused_ops_write_mask & (1 << i)) {
  10213. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  10214. need_sync = true;
  10215. break;
  10216. }
  10217. }
  10218. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10219. if (!cur_node->src[j]) {
  10220. continue;
  10221. }
  10222. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  10223. need_sync = true;
  10224. break;
  10225. }
  10226. }
  10227. }
  10228. if (need_sync) {
  10229. if (vk_enable_sync_logger) {
  10230. std::cerr << "sync" << std::endl;
  10231. }
  10232. ctx->unsynced_nodes_written.clear();
  10233. ctx->unsynced_nodes_read.clear();
  10234. ggml_vk_sync_buffers(ctx, compute_ctx);
  10235. if (vk_perf_logger_enabled && vk_perf_logger_concurrent) {
  10236. ctx->query_node_idx[ctx->query_idx] = node_idx;
  10237. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  10238. }
  10239. }
  10240. // Add all fused nodes to the unsynchronized lists.
  10241. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10242. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10243. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  10244. if (ctx->fused_ops_write_mask & (1 << i)) {
  10245. ctx->unsynced_nodes_written.push_back(cur_node);
  10246. }
  10247. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10248. if (!cur_node->src[j]) {
  10249. continue;
  10250. }
  10251. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  10252. }
  10253. }
  10254. }
  10255. if (vk_enable_sync_logger) {
  10256. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10257. auto *n = cgraph->nodes[node_idx + i];
  10258. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  10259. if (n->op == GGML_OP_GLU) {
  10260. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  10261. }
  10262. if (n->op == GGML_OP_ROPE) {
  10263. const int mode = ((const int32_t *) n->op_params)[2];
  10264. std::cerr << " rope mode: " << mode;
  10265. }
  10266. std::cerr << std::endl;
  10267. }
  10268. }
  10269. switch (node->op) {
  10270. case GGML_OP_REPEAT:
  10271. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  10272. break;
  10273. case GGML_OP_REPEAT_BACK:
  10274. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  10275. break;
  10276. case GGML_OP_ACC:
  10277. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  10278. break;
  10279. case GGML_OP_GET_ROWS:
  10280. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  10281. break;
  10282. case GGML_OP_ADD:
  10283. if (ctx->num_additional_fused_ops) {
  10284. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  10285. } else {
  10286. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  10287. }
  10288. break;
  10289. case GGML_OP_SUB:
  10290. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  10291. break;
  10292. case GGML_OP_MUL:
  10293. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  10294. break;
  10295. case GGML_OP_DIV:
  10296. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  10297. break;
  10298. case GGML_OP_ADD_ID:
  10299. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  10300. break;
  10301. case GGML_OP_CONCAT:
  10302. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  10303. break;
  10304. case GGML_OP_UPSCALE:
  10305. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  10306. break;
  10307. case GGML_OP_ADD1:
  10308. ggml_vk_add1(ctx, compute_ctx, src0, src1, node);
  10309. break;
  10310. case GGML_OP_ARANGE:
  10311. ggml_vk_arange(ctx, compute_ctx, node);
  10312. break;
  10313. case GGML_OP_FILL:
  10314. ggml_vk_fill(ctx, compute_ctx, node);
  10315. break;
  10316. case GGML_OP_SCALE:
  10317. ggml_vk_scale(ctx, compute_ctx, src0, node);
  10318. break;
  10319. case GGML_OP_SQR:
  10320. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  10321. break;
  10322. case GGML_OP_SQRT:
  10323. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  10324. break;
  10325. case GGML_OP_SIN:
  10326. ggml_vk_sin(ctx, compute_ctx, src0, node);
  10327. break;
  10328. case GGML_OP_COS:
  10329. ggml_vk_cos(ctx, compute_ctx, src0, node);
  10330. break;
  10331. case GGML_OP_LOG:
  10332. ggml_vk_log(ctx, compute_ctx, src0, node);
  10333. break;
  10334. case GGML_OP_TRI:
  10335. ggml_vk_tri(ctx, compute_ctx, src0, node);
  10336. break;
  10337. case GGML_OP_DIAG:
  10338. ggml_vk_diag(ctx, compute_ctx, src0, node);
  10339. break;
  10340. case GGML_OP_CLAMP:
  10341. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  10342. break;
  10343. case GGML_OP_PAD:
  10344. ggml_vk_pad(ctx, compute_ctx, src0, node);
  10345. break;
  10346. case GGML_OP_ROLL:
  10347. ggml_vk_roll(ctx, compute_ctx, src0, node);
  10348. break;
  10349. case GGML_OP_CPY:
  10350. case GGML_OP_CONT:
  10351. case GGML_OP_DUP:
  10352. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  10353. break;
  10354. case GGML_OP_SET_ROWS:
  10355. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  10356. break;
  10357. case GGML_OP_SILU_BACK:
  10358. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  10359. break;
  10360. case GGML_OP_NORM:
  10361. ggml_vk_norm(ctx, compute_ctx, src0, node);
  10362. break;
  10363. case GGML_OP_GROUP_NORM:
  10364. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  10365. break;
  10366. case GGML_OP_RMS_NORM:
  10367. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  10368. break;
  10369. case GGML_OP_RMS_NORM_BACK:
  10370. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  10371. break;
  10372. case GGML_OP_L2_NORM:
  10373. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  10374. break;
  10375. case GGML_OP_UNARY:
  10376. switch (ggml_get_unary_op(node)) {
  10377. case GGML_UNARY_OP_EXP:
  10378. case GGML_UNARY_OP_SILU:
  10379. case GGML_UNARY_OP_GELU:
  10380. case GGML_UNARY_OP_GELU_ERF:
  10381. case GGML_UNARY_OP_GELU_QUICK:
  10382. case GGML_UNARY_OP_RELU:
  10383. case GGML_UNARY_OP_NEG:
  10384. case GGML_UNARY_OP_TANH:
  10385. case GGML_UNARY_OP_SIGMOID:
  10386. case GGML_UNARY_OP_HARDSIGMOID:
  10387. case GGML_UNARY_OP_HARDSWISH:
  10388. case GGML_UNARY_OP_ABS:
  10389. case GGML_UNARY_OP_SOFTPLUS:
  10390. case GGML_UNARY_OP_STEP:
  10391. case GGML_UNARY_OP_ROUND:
  10392. case GGML_UNARY_OP_CEIL:
  10393. case GGML_UNARY_OP_FLOOR:
  10394. case GGML_UNARY_OP_TRUNC:
  10395. ggml_vk_unary(ctx, compute_ctx, src0, node);
  10396. break;
  10397. case GGML_UNARY_OP_XIELU:
  10398. ggml_vk_xielu(ctx, compute_ctx, src0, node);
  10399. break;
  10400. default:
  10401. return false;
  10402. }
  10403. break;
  10404. case GGML_OP_GLU:
  10405. switch (ggml_get_glu_op(node)) {
  10406. case GGML_GLU_OP_GEGLU:
  10407. case GGML_GLU_OP_REGLU:
  10408. case GGML_GLU_OP_SWIGLU:
  10409. case GGML_GLU_OP_SWIGLU_OAI:
  10410. case GGML_GLU_OP_GEGLU_ERF:
  10411. case GGML_GLU_OP_GEGLU_QUICK:
  10412. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  10413. break;
  10414. default:
  10415. return false;
  10416. }
  10417. break;
  10418. case GGML_OP_DIAG_MASK_INF:
  10419. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  10420. break;
  10421. case GGML_OP_SOFT_MAX:
  10422. if (ctx->num_additional_fused_ops) {
  10423. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10424. } else {
  10425. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  10426. }
  10427. break;
  10428. case GGML_OP_SOFT_MAX_BACK:
  10429. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  10430. break;
  10431. case GGML_OP_ROPE:
  10432. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  10433. break;
  10434. case GGML_OP_ROPE_BACK:
  10435. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  10436. break;
  10437. case GGML_OP_ARGSORT:
  10438. if (ctx->num_additional_fused_ops) {
  10439. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10440. } else {
  10441. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10442. }
  10443. break;
  10444. case GGML_OP_TOP_K:
  10445. ggml_vk_topk(ctx, compute_ctx, src0, node);
  10446. break;
  10447. case GGML_OP_SUM:
  10448. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10449. break;
  10450. case GGML_OP_SUM_ROWS:
  10451. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10452. break;
  10453. case GGML_OP_CUMSUM:
  10454. ggml_vk_cumsum(ctx, compute_ctx, src0, node);
  10455. break;
  10456. case GGML_OP_MEAN:
  10457. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10458. break;
  10459. case GGML_OP_ARGMAX:
  10460. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10461. break;
  10462. case GGML_OP_COUNT_EQUAL:
  10463. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10464. break;
  10465. case GGML_OP_SOLVE_TRI:
  10466. ggml_vk_solve_tri(ctx, compute_ctx, src0, src1, node);
  10467. break;
  10468. case GGML_OP_IM2COL:
  10469. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10470. break;
  10471. case GGML_OP_IM2COL_3D:
  10472. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10473. break;
  10474. case GGML_OP_TIMESTEP_EMBEDDING:
  10475. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10476. break;
  10477. case GGML_OP_CONV_TRANSPOSE_1D:
  10478. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10479. break;
  10480. case GGML_OP_POOL_2D:
  10481. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10482. break;
  10483. case GGML_OP_CONV_2D:
  10484. case GGML_OP_CONV_TRANSPOSE_2D:
  10485. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10486. break;
  10487. case GGML_OP_CONV_2D_DW:
  10488. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10489. break;
  10490. case GGML_OP_LEAKY_RELU:
  10491. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10492. break;
  10493. case GGML_OP_MUL_MAT:
  10494. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10495. break;
  10496. case GGML_OP_MUL_MAT_ID:
  10497. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10498. break;
  10499. case GGML_OP_FLASH_ATTN_EXT:
  10500. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10501. break;
  10502. case GGML_OP_RWKV_WKV6:
  10503. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10504. break;
  10505. case GGML_OP_RWKV_WKV7:
  10506. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10507. break;
  10508. case GGML_OP_SSM_SCAN:
  10509. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10510. break;
  10511. case GGML_OP_SSM_CONV:
  10512. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10513. break;
  10514. case GGML_OP_OPT_STEP_ADAMW:
  10515. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10516. break;
  10517. case GGML_OP_OPT_STEP_SGD:
  10518. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10519. break;
  10520. default:
  10521. return false;
  10522. }
  10523. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10524. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10525. // Force context reset on each node so that each tensor ends up in its own context
  10526. // and can be run and compared to its CPU equivalent separately
  10527. last_node = true;
  10528. #endif
  10529. if (submit || last_node) {
  10530. ggml_vk_ctx_end(compute_ctx);
  10531. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10532. if (last_node) {
  10533. compute_ctx->exit_tensor_idx = node_idx_begin;
  10534. }
  10535. else {
  10536. compute_ctx->exit_tensor_idx = -1;
  10537. }
  10538. ctx->compute_ctx.reset();
  10539. ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready);
  10540. }
  10541. return true;
  10542. }
  10543. static void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready = false) {
  10544. GGML_UNUSED(cgraph);
  10545. GGML_UNUSED(tensor);
  10546. 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 << ")");
  10547. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10548. // Only run if ctx hasn't been submitted yet
  10549. if (!subctx->seqs.empty()) {
  10550. #ifdef GGML_VULKAN_CHECK_RESULTS
  10551. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10552. #endif
  10553. // Do staging buffer copies
  10554. for (auto& cpy : subctx->in_memcpys) {
  10555. memcpy(cpy.dst, cpy.src, cpy.n);
  10556. }
  10557. for (auto& mset : subctx->memsets) {
  10558. memset(mset.dst, mset.val, mset.n);
  10559. }
  10560. if (almost_ready && !ctx->almost_ready_fence_pending) {
  10561. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10562. ctx->almost_ready_fence_pending = true;
  10563. } else {
  10564. ggml_vk_submit(subctx, {});
  10565. }
  10566. ctx->submit_pending = true;
  10567. #ifdef GGML_VULKAN_CHECK_RESULTS
  10568. ggml_vk_synchronize(ctx);
  10569. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10570. #endif
  10571. }
  10572. if (tensor_idx == subctx->exit_tensor_idx) {
  10573. // Do staging buffer copies
  10574. for (auto& cpy : subctx->out_memcpys) {
  10575. memcpy(cpy.dst, cpy.src, cpy.n);
  10576. }
  10577. subctx->in_memcpys.clear();
  10578. subctx->out_memcpys.clear();
  10579. subctx->memsets.clear();
  10580. }
  10581. }
  10582. // Clean up after graph processing is done
  10583. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10584. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10585. ctx->prealloc_y_last_pipeline_used = {};
  10586. ctx->unsynced_nodes_written.clear();
  10587. ctx->unsynced_nodes_read.clear();
  10588. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10589. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10590. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10591. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10592. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10593. }
  10594. ctx->gc.semaphores.clear();
  10595. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10596. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10597. }
  10598. ctx->gc.tl_semaphores.clear();
  10599. ctx->semaphore_idx = 0;
  10600. ctx->event_idx = 0;
  10601. for (auto& event : ctx->gc.events) {
  10602. ctx->device->device.resetEvent(event);
  10603. }
  10604. ctx->tensor_ctxs.clear();
  10605. ctx->gc.contexts.clear();
  10606. ctx->pipeline_descriptor_set_requirements = 0;
  10607. ctx->descriptor_set_idx = 0;
  10608. }
  10609. // Clean up on backend free
  10610. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10611. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10612. // discard any unsubmitted command buffers
  10613. ctx->transfer_ctx.reset();
  10614. // wait for any pending command buffers to finish
  10615. ggml_vk_synchronize(ctx);
  10616. ggml_vk_graph_cleanup(ctx);
  10617. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10618. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10619. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10620. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10621. ggml_vk_destroy_buffer(ctx->sync_staging);
  10622. ctx->prealloc_y_last_pipeline_used = nullptr;
  10623. ctx->prealloc_size_x = 0;
  10624. ctx->prealloc_size_y = 0;
  10625. ctx->prealloc_size_split_k = 0;
  10626. for (auto& event : ctx->gc.events) {
  10627. ctx->device->device.destroyEvent(event);
  10628. }
  10629. ctx->gc.events.clear();
  10630. ctx->device->device.destroyFence(ctx->fence);
  10631. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10632. for (auto& pool : ctx->descriptor_pools) {
  10633. ctx->device->device.destroyDescriptorPool(pool);
  10634. }
  10635. ctx->descriptor_pools.clear();
  10636. ctx->descriptor_sets.clear();
  10637. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10638. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10639. if (vk_perf_logger_enabled) {
  10640. ctx->perf_logger->print_timings(true);
  10641. }
  10642. }
  10643. static int ggml_vk_get_device_count() {
  10644. ggml_vk_instance_init();
  10645. return vk_instance.device_indices.size();
  10646. }
  10647. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10648. ggml_vk_instance_init();
  10649. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10650. vk::PhysicalDeviceProperties props;
  10651. devices[device].getProperties(&props);
  10652. snprintf(description, description_size, "%s", props.deviceName.data());
  10653. }
  10654. // backend interface
  10655. #define UNUSED GGML_UNUSED
  10656. // device backend
  10657. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10658. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10659. }
  10660. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10661. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10662. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10663. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10664. delete ctx;
  10665. }
  10666. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10667. return vk_ptr_base;
  10668. UNUSED(buffer);
  10669. }
  10670. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10671. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10672. if (tensor->view_src != nullptr) {
  10673. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10674. }
  10675. return GGML_STATUS_SUCCESS;
  10676. }
  10677. 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) {
  10678. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10679. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10680. vk_buffer buf = buf_ctx->dev_buffer;
  10681. uint32_t val32 = (uint32_t)value * 0x01010101;
  10682. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10683. }
  10684. 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) {
  10685. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10686. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10687. vk_buffer buf = buf_ctx->dev_buffer;
  10688. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10689. }
  10690. 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) {
  10691. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10692. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10693. vk_buffer buf = buf_ctx->dev_buffer;
  10694. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10695. }
  10696. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10697. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10698. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10699. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10700. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10701. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10702. 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));
  10703. return true;
  10704. }
  10705. return false;
  10706. UNUSED(buffer);
  10707. }
  10708. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10709. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10710. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10711. }
  10712. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10713. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10714. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10715. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10716. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10717. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10718. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10719. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10720. /* .clear = */ ggml_backend_vk_buffer_clear,
  10721. /* .reset = */ NULL,
  10722. };
  10723. // vk buffer type
  10724. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10725. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10726. return ctx->name.c_str();
  10727. }
  10728. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10729. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10730. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10731. vk_buffer dev_buffer = nullptr;
  10732. try {
  10733. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10734. } catch (const vk::SystemError& e) {
  10735. return nullptr;
  10736. }
  10737. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10738. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10739. }
  10740. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10741. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10742. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10743. }
  10744. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10745. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10746. return ctx->device->suballocation_block_size;
  10747. }
  10748. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10749. return ggml_nbytes(tensor);
  10750. UNUSED(buft);
  10751. }
  10752. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10753. ggml_vk_instance_init();
  10754. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10755. vk_device dev = ggml_vk_get_device(dev_num);
  10756. return &dev->buffer_type;
  10757. }
  10758. // host buffer type
  10759. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10760. return GGML_VK_NAME "_Host";
  10761. UNUSED(buft);
  10762. }
  10763. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10764. return GGML_VK_NAME "_Host";
  10765. UNUSED(buffer);
  10766. }
  10767. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10768. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10769. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10770. }
  10771. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10772. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10773. size += 32; // Behave like the CPU buffer type
  10774. void * ptr = nullptr;
  10775. try {
  10776. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10777. } catch (vk::SystemError& e) {
  10778. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10779. // fallback to cpu buffer
  10780. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10781. }
  10782. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10783. buffer->buft = buft;
  10784. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10785. return buffer;
  10786. UNUSED(buft);
  10787. }
  10788. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10789. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10790. UNUSED(buft);
  10791. }
  10792. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10793. return vk_instance.devices[0]->suballocation_block_size;
  10794. UNUSED(buft);
  10795. }
  10796. // Should be changed to return device-specific host buffer type
  10797. // but that probably requires changes in llama.cpp
  10798. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10799. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10800. /* .iface = */ {
  10801. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10802. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10803. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10804. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10805. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10806. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10807. },
  10808. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10809. /* .context = */ nullptr,
  10810. };
  10811. // Make sure device 0 is initialized
  10812. ggml_vk_instance_init();
  10813. ggml_vk_get_device(0);
  10814. return &ggml_backend_vk_buffer_type_host;
  10815. }
  10816. // backend
  10817. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10818. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10819. return ctx->name.c_str();
  10820. }
  10821. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10822. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10823. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10824. ggml_vk_cleanup(ctx);
  10825. delete ctx;
  10826. delete backend;
  10827. }
  10828. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10829. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10830. return &ctx->device->buffer_type;
  10831. }
  10832. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10833. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10834. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10835. 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");
  10836. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10837. vk_context transfer_ctx;
  10838. if (ctx->transfer_ctx.expired()) {
  10839. // Initialize new transfer context
  10840. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10841. ctx->transfer_ctx = transfer_ctx;
  10842. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10843. } else {
  10844. transfer_ctx = ctx->transfer_ctx.lock();
  10845. }
  10846. vk_buffer buf = buf_ctx->dev_buffer;
  10847. auto dst_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  10848. bool ret = ggml_vk_buffer_write_async(transfer_ctx, buf, dst_offset, data, size);
  10849. if (!ret) {
  10850. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  10851. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  10852. vk::BufferCopy buffer_cpy;
  10853. buffer_cpy.srcOffset = 0;
  10854. buffer_cpy.dstOffset = dst_offset;
  10855. buffer_cpy.size = size;
  10856. transfer_ctx->s->buffer.copyBuffer(ctx->sync_staging->buffer, buf->buffer, { buffer_cpy });
  10857. deferred_memcpy(ctx->sync_staging->ptr, data, size, &transfer_ctx->in_memcpys);
  10858. ggml_vk_synchronize(ctx);
  10859. }
  10860. }
  10861. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10862. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10863. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10864. 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");
  10865. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10866. vk_context transfer_ctx;
  10867. if (ctx->transfer_ctx.expired()) {
  10868. // Initialize new transfer context
  10869. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10870. ctx->transfer_ctx = transfer_ctx;
  10871. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10872. } else {
  10873. transfer_ctx = ctx->transfer_ctx.lock();
  10874. }
  10875. vk_buffer buf = buf_ctx->dev_buffer;
  10876. auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  10877. bool ret = ggml_vk_buffer_read_async(transfer_ctx, buf, src_offset, data, size);
  10878. // If that failed, copy synchronously through a staging buffer
  10879. if (!ret) {
  10880. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  10881. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  10882. vk::BufferCopy buffer_cpy;
  10883. buffer_cpy.srcOffset = src_offset;
  10884. buffer_cpy.dstOffset = 0;
  10885. buffer_cpy.size = size;
  10886. transfer_ctx->s->buffer.copyBuffer(buf->buffer, ctx->sync_staging->buffer, { buffer_cpy });
  10887. deferred_memcpy(data, ctx->sync_staging->ptr, size, &transfer_ctx->out_memcpys);
  10888. ggml_vk_synchronize(ctx);
  10889. }
  10890. }
  10891. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10892. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10893. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10894. 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)) {
  10895. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10896. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10897. vk_context transfer_ctx;
  10898. if (ctx->transfer_ctx.expired()) {
  10899. // Initialize new transfer context
  10900. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10901. ctx->transfer_ctx = transfer_ctx;
  10902. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10903. } else {
  10904. transfer_ctx = ctx->transfer_ctx.lock();
  10905. }
  10906. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10907. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10908. 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));
  10909. return true;
  10910. }
  10911. return false;
  10912. }
  10913. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx) {
  10914. VK_LOG_DEBUG("ggml_vk_synchronize()");
  10915. bool do_transfer = !ctx->transfer_ctx.expired();
  10916. vk_context transfer_ctx;
  10917. if (do_transfer) {
  10918. transfer_ctx = ctx->transfer_ctx.lock();
  10919. ggml_vk_ctx_end(transfer_ctx);
  10920. for (auto& cpy : transfer_ctx->in_memcpys) {
  10921. memcpy(cpy.dst, cpy.src, cpy.n);
  10922. }
  10923. ggml_vk_submit(transfer_ctx, {});
  10924. ctx->submit_pending = true;
  10925. }
  10926. if (ctx->submit_pending) {
  10927. {
  10928. std::lock_guard<std::mutex> guard(queue_mutex);
  10929. ctx->device->compute_queue.queue.submit({}, ctx->fence);
  10930. }
  10931. ggml_vk_wait_for_fence(ctx);
  10932. ctx->submit_pending = false;
  10933. }
  10934. if (do_transfer) {
  10935. for (auto& cpy : transfer_ctx->out_memcpys) {
  10936. memcpy(cpy.dst, cpy.src, cpy.n);
  10937. }
  10938. ctx->transfer_ctx.reset();
  10939. }
  10940. }
  10941. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10942. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10943. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10944. ggml_vk_synchronize(ctx);
  10945. ggml_vk_graph_cleanup(ctx);
  10946. }
  10947. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10948. 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;
  10949. }
  10950. 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) {
  10951. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10952. return false;
  10953. }
  10954. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10955. // additional constraints specific to this fusion
  10956. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10957. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10958. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10959. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10960. // rms_norm only supports f32
  10961. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10962. mul->src[1]->type != GGML_TYPE_F32 ||
  10963. mul->type != GGML_TYPE_F32) {
  10964. return false;
  10965. }
  10966. // if rms_norm is the B operand, then we don't handle broadcast
  10967. if (rms_norm == mul->src[1] &&
  10968. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10969. return false;
  10970. }
  10971. // rms_norm shader assumes contiguous rows
  10972. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10973. return false;
  10974. }
  10975. }
  10976. auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) {
  10977. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  10978. // mat-vec only
  10979. if (ggml_nrows(mul) != 1) {
  10980. return false;
  10981. }
  10982. // shaders assume the types match
  10983. if (mul->type != bias->type) {
  10984. return false;
  10985. }
  10986. // shaders reuse the D shape for bias
  10987. if (!ggml_are_same_shape(mul, bias) ||
  10988. !ggml_are_same_stride(mul, bias)) {
  10989. return false;
  10990. }
  10991. // unaligned bias isn't handled
  10992. if (get_misalign_bytes(ctx, bias) != 0) {
  10993. return false;
  10994. }
  10995. return true;
  10996. };
  10997. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  10998. // additional constraints specific to this fusion
  10999. const ggml_tensor *mul = cgraph->nodes[node_idx];
  11000. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  11001. if (!mm_add_ok(mul, add)) {
  11002. return false;
  11003. }
  11004. if (ops.size() == 3) {
  11005. if (ops.begin()[2] != GGML_OP_ADD) {
  11006. return false;
  11007. }
  11008. if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) {
  11009. return false;
  11010. }
  11011. }
  11012. }
  11013. auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) {
  11014. const ggml_tensor *scale = mul->src[1];
  11015. if (mmid != mul->src[0]) {
  11016. return false;
  11017. }
  11018. // mat-vec only
  11019. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  11020. return false;
  11021. }
  11022. // shaders assume the types match
  11023. if (mmid->type != scale->type) {
  11024. return false;
  11025. }
  11026. // shaders assume the bias is contiguous
  11027. if (!ggml_is_contiguous(scale)) {
  11028. return false;
  11029. }
  11030. // unaligned bias isn't handled
  11031. if (get_misalign_bytes(ctx, scale) != 0) {
  11032. return false;
  11033. }
  11034. // shader only indexes by expert index
  11035. if (scale->ne[0] != 1 ||
  11036. scale->ne[1] != mul->ne[1] ||
  11037. scale->ne[2] != 1 ||
  11038. scale->ne[3] != 1) {
  11039. return false;
  11040. }
  11041. return true;
  11042. };
  11043. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  11044. // additional constraints specific to this fusion
  11045. const ggml_tensor *mul = cgraph->nodes[node_idx];
  11046. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  11047. const ggml_tensor *bias = add->src[1];
  11048. if (mul != add->src[0]) {
  11049. return false;
  11050. }
  11051. // mat-vec only
  11052. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  11053. return false;
  11054. }
  11055. // shaders assume the types match
  11056. if (mul->type != bias->type) {
  11057. return false;
  11058. }
  11059. // shaders assume the bias is contiguous
  11060. if (!ggml_is_contiguous(bias)) {
  11061. return false;
  11062. }
  11063. // the ID tensor must be the same for mul_mat_id and add_id
  11064. if (mul->src[2] != add->src[2]) {
  11065. return false;
  11066. }
  11067. // unaligned bias isn't handled
  11068. if (get_misalign_bytes(ctx, bias) != 0) {
  11069. return false;
  11070. }
  11071. if (ops.size() == 3) {
  11072. if (ops.begin()[2] != GGML_OP_MUL) {
  11073. return false;
  11074. }
  11075. const ggml_tensor *mul = cgraph->nodes[node_idx + 2];
  11076. return mmid_mul_ok(add, mul);
  11077. }
  11078. }
  11079. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  11080. // additional constraints specific to this fusion
  11081. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  11082. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11083. if (!mmid_mul_ok(mmid, mul)) {
  11084. return false;
  11085. }
  11086. }
  11087. return true;
  11088. }
  11089. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11090. int node_idx, topk_moe_mode mode) {
  11091. const ggml_tensor * softmax;
  11092. const ggml_tensor * weights;
  11093. const ggml_tensor * get_rows;
  11094. const ggml_tensor * argsort;
  11095. switch (mode) {
  11096. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  11097. softmax = cgraph->nodes[node_idx + 0];
  11098. weights = cgraph->nodes[node_idx + 9];
  11099. get_rows = cgraph->nodes[node_idx + 4];
  11100. argsort = cgraph->nodes[node_idx + 2];
  11101. break;
  11102. case TOPK_MOE_EARLY_SOFTMAX:
  11103. softmax = cgraph->nodes[node_idx + 0];
  11104. weights = cgraph->nodes[node_idx + 4];
  11105. get_rows = cgraph->nodes[node_idx + 4];
  11106. argsort = cgraph->nodes[node_idx + 2];
  11107. break;
  11108. case TOPK_MOE_LATE_SOFTMAX:
  11109. softmax = cgraph->nodes[node_idx + 4];
  11110. weights = cgraph->nodes[node_idx + 5];
  11111. get_rows = cgraph->nodes[node_idx + 2];
  11112. argsort = cgraph->nodes[node_idx + 0];
  11113. break;
  11114. default:
  11115. return false;
  11116. }
  11117. ggml_tensor * probs = get_rows->src[0];
  11118. if (probs->op != GGML_OP_RESHAPE) {
  11119. return false;
  11120. }
  11121. probs = probs->src[0];
  11122. ggml_tensor * selection_probs = argsort->src[0];
  11123. if (probs != selection_probs) {
  11124. return false;
  11125. }
  11126. const float * op_params = (const float *)softmax->op_params;
  11127. float scale = op_params[0];
  11128. float max_bias = op_params[1];
  11129. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  11130. return false;
  11131. }
  11132. if (scale != 1.0f || max_bias != 0.0f) {
  11133. return false;
  11134. }
  11135. // don't fuse when masks or sinks are present
  11136. if (softmax->src[1] || softmax->src[2]) {
  11137. return false;
  11138. }
  11139. const int n_expert = softmax->ne[0];
  11140. if (n_expert > (1 << (num_topk_moe_pipelines-1))) {
  11141. return false;
  11142. }
  11143. if (!ctx->device->subgroup_arithmetic ||
  11144. !ctx->device->subgroup_shuffle ||
  11145. !ctx->device->subgroup_require_full_support ||
  11146. ctx->device->disable_fusion) {
  11147. return false;
  11148. }
  11149. return true;
  11150. }
  11151. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11152. int node_idx) {
  11153. GGML_UNUSED(ctx);
  11154. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  11155. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  11156. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  11157. // ne3 not tested
  11158. if (rope->src[0]->ne[3] != 1) {
  11159. return false;
  11160. }
  11161. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  11162. return false;
  11163. }
  11164. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  11165. return false;
  11166. }
  11167. // The view should flatten two dims of rope into one dim
  11168. if (!ggml_is_contiguous(view) ||
  11169. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  11170. return false;
  11171. }
  11172. // Only norm/neox/mrope shaders have the fusion code
  11173. const int mode = ((const int32_t *) rope->op_params)[2];
  11174. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_MROPE) {
  11175. return false;
  11176. }
  11177. return true;
  11178. }
  11179. // Check whether the tensors overlap in memory but are not equal.
  11180. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  11181. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  11182. // to overlap if they are exactly equal.
  11183. // XXX TODO this check is probably missing from several fusion optimizations.
  11184. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  11185. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  11186. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  11187. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  11188. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  11189. if (a_buf == b_buf) {
  11190. auto a_base = vk_tensor_offset(a) + a->view_offs;
  11191. auto a_size = ggml_nbytes(a);
  11192. auto b_base = vk_tensor_offset(b) + b->view_offs;
  11193. auto b_size = ggml_nbytes(b);
  11194. if (a_base == b_base && a_size == b_size) {
  11195. return false;
  11196. }
  11197. if ((b_base <= a_base && a_base < b_base + b_size) ||
  11198. (a_base <= b_base && b_base < a_base + a_size)) {
  11199. return true;
  11200. }
  11201. }
  11202. return false;
  11203. }
  11204. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11205. int node_idx) {
  11206. GGML_UNUSED(ctx);
  11207. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  11208. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11209. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  11210. const int mode = ((const int32_t *) rope->op_params)[2];
  11211. // noncontig tensors aren't tested, and don't seem common in practice
  11212. if (!ggml_is_contiguous(rms) ||
  11213. !ggml_is_contiguous(mul) ||
  11214. !ggml_is_contiguous(rope)) {
  11215. return false;
  11216. }
  11217. // only norm/neox are handled in the shader
  11218. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  11219. return false;
  11220. }
  11221. // shared memory size for passing data from mul->rope
  11222. if (mul->ne[0] > 1024) {
  11223. return false;
  11224. }
  11225. // must not overwrite srcs in a way that's not elementwise
  11226. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  11227. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  11228. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  11229. return false;
  11230. }
  11231. // conditions for pipeline creation
  11232. if (!(ctx->device->float_controls_rte_fp16 &&
  11233. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= ctx->device->properties.limits.maxPushConstantsSize)) {
  11234. return false;
  11235. }
  11236. return true;
  11237. }
  11238. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  11239. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  11240. if (first_node->op != GGML_OP_ADD) {
  11241. return 0;
  11242. }
  11243. if (!ctx->device->multi_add) {
  11244. return 0;
  11245. }
  11246. int32_t num_adds = 1;
  11247. while (node_idx + num_adds < cgraph->n_nodes &&
  11248. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  11249. num_adds < MAX_FUSED_ADDS) {
  11250. num_adds++;
  11251. }
  11252. // The shader currently requires same shapes (but different strides are allowed),
  11253. // everything f32, and no misalignment
  11254. for (int32_t i = 0; i < num_adds; ++i) {
  11255. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  11256. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  11257. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  11258. next_node->type != GGML_TYPE_F32 ||
  11259. next_node->src[0]->type != GGML_TYPE_F32 ||
  11260. next_node->src[1]->type != GGML_TYPE_F32 ||
  11261. get_misalign_bytes(ctx, next_node) ||
  11262. get_misalign_bytes(ctx, next_node->src[0]) ||
  11263. get_misalign_bytes(ctx, next_node->src[1])) {
  11264. num_adds = i;
  11265. }
  11266. }
  11267. // Verify we can fuse these
  11268. ggml_op adds[MAX_FUSED_ADDS];
  11269. for (int32_t i = 0; i < num_adds; ++i) {
  11270. adds[i] = GGML_OP_ADD;
  11271. }
  11272. // decrease num_adds if they can't all be fused
  11273. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  11274. num_adds--;
  11275. }
  11276. // a single add is not "fused", so just return zero
  11277. if (num_adds == 1) {
  11278. return 0;
  11279. }
  11280. return num_adds;
  11281. }
  11282. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  11283. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  11284. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11285. if (vk_instance.debug_utils_support) {
  11286. vk::DebugUtilsLabelEXT dul = {};
  11287. dul.pLabelName = "ggml_backend_vk_graph_compute";
  11288. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  11289. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  11290. }
  11291. ctx->prealloc_size_add_rms_partials_offset = 0;
  11292. ctx->do_add_rms_partials = false;
  11293. ctx->do_add_rms_partials_offset_calculation = false;
  11294. int last_node = cgraph->n_nodes - 1;
  11295. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  11296. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  11297. last_node -= 1;
  11298. }
  11299. // Reserve tensor context space for all nodes
  11300. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  11301. bool first_node_in_batch = true; // true if next node will be first node in a batch
  11302. int submit_node_idx = 0; // index to first node in a batch
  11303. vk_context compute_ctx;
  11304. if (vk_perf_logger_enabled) {
  11305. // allocate/resize the query pool
  11306. if (ctx->num_queries < cgraph->n_nodes + 1) {
  11307. if (ctx->query_pool) {
  11308. ctx->device->device.destroyQueryPool(ctx->query_pool);
  11309. }
  11310. vk::QueryPoolCreateInfo query_create_info;
  11311. query_create_info.queryType = vk::QueryType::eTimestamp;
  11312. query_create_info.queryCount = cgraph->n_nodes + 100;
  11313. ctx->query_pool = ctx->device->device.createQueryPool(query_create_info);
  11314. ctx->num_queries = query_create_info.queryCount;
  11315. ctx->query_fusion_names.resize(ctx->num_queries);
  11316. ctx->query_fusion_node_count.resize(ctx->num_queries);
  11317. ctx->query_nodes.resize(ctx->num_queries);
  11318. ctx->query_node_idx.resize(ctx->num_queries);
  11319. }
  11320. ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1);
  11321. std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr);
  11322. std::fill(ctx->query_fusion_node_count.begin(), ctx->query_fusion_node_count.end(), 0);
  11323. std::fill(ctx->query_nodes.begin(), ctx->query_nodes.end(), nullptr);
  11324. std::fill(ctx->query_node_idx.begin(), ctx->query_node_idx.end(), 0);
  11325. GGML_ASSERT(ctx->compute_ctx.expired());
  11326. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11327. ctx->compute_ctx = compute_ctx;
  11328. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11329. ctx->query_idx = 0;
  11330. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11331. }
  11332. ctx->prealloc_y_last_pipeline_used = nullptr;
  11333. ctx->prealloc_y_last_tensor_used = nullptr;
  11334. if (ctx->prealloc_size_add_rms_partials) {
  11335. ggml_vk_preallocate_buffers(ctx, nullptr);
  11336. if (ctx->compute_ctx.expired()) {
  11337. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11338. ctx->compute_ctx = compute_ctx;
  11339. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11340. } else {
  11341. compute_ctx = ctx->compute_ctx.lock();
  11342. }
  11343. // initialize partial sums to zero.
  11344. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  11345. ggml_vk_sync_buffers(ctx, compute_ctx);
  11346. }
  11347. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  11348. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  11349. // (and scaled down based on model size, so smaller models submit earlier).
  11350. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  11351. int nodes_per_submit = 100;
  11352. int submitted_nodes = 0;
  11353. int submit_count = 0;
  11354. uint64_t mul_mat_bytes = 0;
  11355. uint64_t total_mul_mat_bytes = 0;
  11356. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  11357. for (int i = 0; i < cgraph->n_nodes; i++) {
  11358. if (first_node_in_batch) {
  11359. submit_node_idx = i;
  11360. }
  11361. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11362. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  11363. mul_mat_bytes += bytes;
  11364. total_mul_mat_bytes += bytes;
  11365. }
  11366. const char *fusion_string {};
  11367. if (!ctx->device->disable_fusion) {
  11368. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11369. if (num_adds) {
  11370. ctx->num_additional_fused_ops = num_adds - 1;
  11371. fusion_string = "MULTI_ADD";
  11372. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) {
  11373. ctx->num_additional_fused_ops = 2;
  11374. fusion_string = "MUL_MAT_ADD_ADD";
  11375. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11376. ctx->num_additional_fused_ops = 1;
  11377. fusion_string = "MUL_MAT_ADD";
  11378. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) {
  11379. ctx->num_additional_fused_ops = 2;
  11380. fusion_string = "MUL_MAT_ID_ADD_ID_MUL";
  11381. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11382. ctx->num_additional_fused_ops = 1;
  11383. fusion_string = "MUL_MAT_ID_ADD_ID";
  11384. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  11385. ctx->num_additional_fused_ops = 1;
  11386. fusion_string = "MUL_MAT_ID_MUL";
  11387. } 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 }) &&
  11388. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  11389. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  11390. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  11391. ctx->num_additional_fused_ops = 4;
  11392. fusion_string = "RMS_NORM_MUL_ROPE_VIEW_SET_ROWS";
  11393. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  11394. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  11395. ctx->num_additional_fused_ops = 2;
  11396. fusion_string = "RMS_NORM_MUL_ROPE";
  11397. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11398. ctx->num_additional_fused_ops = 1;
  11399. fusion_string = "RMS_NORM_MUL";
  11400. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11401. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11402. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11403. ctx->num_additional_fused_ops = 2;
  11404. fusion_string = "ROPE_VIEW_SET_ROWS";
  11405. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11406. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11407. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11408. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11409. // view of argsort writes to memory
  11410. ctx->fused_ops_write_mask |= 1 << 3;
  11411. fusion_string = "TOPK_MOE_EARLY_SOFTMAX_NORM";
  11412. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11413. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11414. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11415. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11416. // view of argsort writes to memory
  11417. ctx->fused_ops_write_mask |= 1 << 3;
  11418. fusion_string = "TOPK_MOE_EARLY_SOFTMAX";
  11419. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11420. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11421. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11422. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11423. // view of argsort writes to memory
  11424. ctx->fused_ops_write_mask |= 1 << 1;
  11425. fusion_string = "TOPK_MOE_LATE_SOFTMAX";
  11426. }
  11427. }
  11428. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  11429. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  11430. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  11431. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11432. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11433. (i + ctx->num_additional_fused_ops >= last_node) ||
  11434. (almost_ready && !ctx->almost_ready_fence_pending);
  11435. 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);
  11436. if (vk_perf_logger_enabled && enqueued) {
  11437. if (ctx->compute_ctx.expired()) {
  11438. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11439. ctx->compute_ctx = compute_ctx;
  11440. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11441. } else {
  11442. compute_ctx = ctx->compute_ctx.lock();
  11443. }
  11444. if (!vk_perf_logger_concurrent) {
  11445. // track a single node/fusion for the current query
  11446. ctx->query_nodes[ctx->query_idx] = cgraph->nodes[i];
  11447. ctx->query_fusion_names[ctx->query_idx] = fusion_string;
  11448. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11449. } else {
  11450. // track a fusion string and number of fused ops for the current node_idx
  11451. ctx->query_fusion_names[i] = fusion_string;
  11452. ctx->query_fusion_node_count[i] = ctx->num_additional_fused_ops;
  11453. }
  11454. }
  11455. if (enqueued) {
  11456. ++submitted_nodes;
  11457. #ifndef GGML_VULKAN_CHECK_RESULTS
  11458. if (first_node_in_batch) {
  11459. first_node_in_batch = false;
  11460. }
  11461. #endif
  11462. }
  11463. if (submit && enqueued) {
  11464. first_node_in_batch = true;
  11465. submitted_nodes = 0;
  11466. mul_mat_bytes = 0;
  11467. if (submit_count < 3) {
  11468. mul_mat_bytes_per_submit *= 2;
  11469. }
  11470. submit_count++;
  11471. }
  11472. i += ctx->num_additional_fused_ops;
  11473. ctx->num_additional_fused_ops = 0;
  11474. ctx->fused_ops_write_mask = 0;
  11475. }
  11476. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11477. if (vk_perf_logger_enabled) {
  11478. // End the command buffer and submit/wait
  11479. GGML_ASSERT(!ctx->compute_ctx.expired());
  11480. compute_ctx = ctx->compute_ctx.lock();
  11481. ggml_vk_ctx_end(compute_ctx);
  11482. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11483. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11484. ctx->device->device.resetFences({ ctx->device->fence });
  11485. // Get the results and pass them to the logger
  11486. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11487. 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");
  11488. if (!vk_perf_logger_concurrent) {
  11489. // Log each op separately
  11490. for (int i = 1; i < ctx->query_idx; i++) {
  11491. auto node = ctx->query_nodes[i];
  11492. auto name = ctx->query_fusion_names[i];
  11493. ctx->perf_logger->log_timing(node, name, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11494. }
  11495. } else {
  11496. // Log each group of nodes
  11497. int prev_node_idx = 0;
  11498. for (int i = 1; i < ctx->query_idx; i++) {
  11499. auto cur_node_idx = ctx->query_node_idx[i];
  11500. std::vector<ggml_tensor *> nodes;
  11501. std::vector<const char *> names;
  11502. for (int node_idx = prev_node_idx; node_idx < cur_node_idx; ++node_idx) {
  11503. if (ggml_op_is_empty(cgraph->nodes[node_idx]->op)) {
  11504. continue;
  11505. }
  11506. nodes.push_back(cgraph->nodes[node_idx]);
  11507. names.push_back(ctx->query_fusion_names[node_idx]);
  11508. node_idx += ctx->query_fusion_node_count[node_idx];
  11509. }
  11510. prev_node_idx = cur_node_idx;
  11511. ctx->perf_logger->log_timing(nodes, names, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11512. }
  11513. }
  11514. ctx->perf_logger->print_timings();
  11515. }
  11516. if (!ctx->device->support_async) {
  11517. ggml_vk_synchronize(ctx);
  11518. }
  11519. return GGML_STATUS_SUCCESS;
  11520. UNUSED(backend);
  11521. }
  11522. // Sort the graph for improved parallelism.
  11523. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11524. {
  11525. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11526. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11527. if (ctx->device->disable_graph_optimize) {
  11528. return;
  11529. }
  11530. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11531. 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;
  11532. };
  11533. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11534. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11535. if (dst->src[s] == src) {
  11536. return true;
  11537. }
  11538. }
  11539. // implicit dependency if they view the same tensor
  11540. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11541. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11542. if (dst2 == src2) {
  11543. return true;
  11544. }
  11545. return false;
  11546. };
  11547. std::vector<ggml_tensor *> new_order;
  11548. std::vector<bool> used(graph->n_nodes, false);
  11549. std::set<ggml_tensor *> used_node_set;
  11550. int first_unused = 0;
  11551. while (first_unused < graph->n_nodes) {
  11552. std::vector<int> current_set;
  11553. // Check for fusion patterns and avoid reordering them
  11554. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11555. if (start + (int)pattern.size() <= graph->n_nodes) {
  11556. bool is_pattern = true;
  11557. for (size_t j = 0; j < pattern.size(); ++j) {
  11558. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11559. is_pattern = false;
  11560. }
  11561. }
  11562. return is_pattern;
  11563. }
  11564. return false;
  11565. };
  11566. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11567. if (match_pattern(pattern, first_unused)) {
  11568. for (size_t j = 0; j < pattern.size(); ++j) {
  11569. new_order.push_back(graph->nodes[first_unused + j]);
  11570. used_node_set.insert(graph->nodes[first_unused + j]);
  11571. used[first_unused + j] = true;
  11572. }
  11573. while (first_unused < graph->n_nodes && used[first_unused]) {
  11574. first_unused++;
  11575. }
  11576. return true;
  11577. }
  11578. return false;
  11579. };
  11580. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11581. continue;
  11582. }
  11583. if (keep_pattern(topk_moe_early_softmax)) {
  11584. continue;
  11585. }
  11586. if (keep_pattern(topk_moe_late_softmax)) {
  11587. continue;
  11588. }
  11589. // First, grab the next unused node.
  11590. current_set.push_back(first_unused);
  11591. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11592. // haven't already been run. Nodes that have already been run have used[i] set
  11593. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11594. // that we support (e.g. RMS_NORM + MUL).
  11595. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11596. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11597. const int NUM_TO_CHECK = 20;
  11598. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11599. if (used[j]) {
  11600. continue;
  11601. }
  11602. if (is_empty(graph->nodes[j])) {
  11603. continue;
  11604. }
  11605. // Don't pull forward nodes from fusion patterns
  11606. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11607. match_pattern(topk_moe_early_softmax, j) ||
  11608. match_pattern(topk_moe_late_softmax, j)) {
  11609. continue;
  11610. }
  11611. bool ok = true;
  11612. for (int c = first_unused; c < j; ++c) {
  11613. if (!used[c] &&
  11614. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11615. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11616. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11617. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11618. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL) &&
  11619. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_ADD && graph->nodes[j]->op == GGML_OP_ADD)) {
  11620. ok = false;
  11621. break;
  11622. }
  11623. }
  11624. if (ok) {
  11625. current_set.push_back(j);
  11626. int rope_idx = j;
  11627. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11628. if (j > 0 &&
  11629. graph->nodes[j]->op == GGML_OP_MUL &&
  11630. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11631. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11632. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11633. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11634. // Check that other srcs are already valid
  11635. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11636. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11637. rope_idx = k;
  11638. current_set.push_back(rope_idx);
  11639. used[rope_idx] = true;
  11640. break;
  11641. }
  11642. }
  11643. }
  11644. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11645. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11646. int view_idx = -1;
  11647. int set_rows_idx = -1;
  11648. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11649. if (view_idx == -1 &&
  11650. graph->nodes[k]->op == GGML_OP_VIEW &&
  11651. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11652. view_idx = k;
  11653. continue;
  11654. }
  11655. if (view_idx != -1 &&
  11656. set_rows_idx == -1 &&
  11657. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11658. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11659. set_rows_idx = k;
  11660. break;
  11661. }
  11662. }
  11663. if (set_rows_idx != -1) {
  11664. current_set.push_back(view_idx);
  11665. current_set.push_back(set_rows_idx);
  11666. used[view_idx] = true;
  11667. used[set_rows_idx] = true;
  11668. }
  11669. }
  11670. // Look for MUL_MAT_ID + ADD_ID + MUL
  11671. if (j > 0 &&
  11672. graph->nodes[j]->op == GGML_OP_ADD_ID &&
  11673. graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) {
  11674. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11675. if (graph->nodes[k]->op == GGML_OP_MUL &&
  11676. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11677. // src1 must either be weights or already processed
  11678. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11679. current_set.push_back(k);
  11680. used[k] = true;
  11681. break;
  11682. }
  11683. }
  11684. }
  11685. // Look for MUL_MAT + ADD + ADD
  11686. if (j > 0 &&
  11687. graph->nodes[j]->op == GGML_OP_ADD &&
  11688. graph->nodes[j-1]->op == GGML_OP_MUL_MAT) {
  11689. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11690. if (graph->nodes[k]->op == GGML_OP_ADD &&
  11691. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11692. // src1 must either be weights or already processed
  11693. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11694. current_set.push_back(k);
  11695. used[k] = true;
  11696. break;
  11697. }
  11698. }
  11699. }
  11700. }
  11701. }
  11702. // Second pass grabs view nodes.
  11703. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11704. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11705. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11706. if (used[j]) {
  11707. continue;
  11708. }
  11709. if (!is_empty(graph->nodes[j])) {
  11710. continue;
  11711. }
  11712. bool ok = true;
  11713. for (int c = first_unused; c < j; ++c) {
  11714. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11715. // skip views whose srcs haven't been processed.
  11716. if (!used[c] &&
  11717. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11718. !c_in_current_set) {
  11719. ok = false;
  11720. break;
  11721. }
  11722. }
  11723. if (ok) {
  11724. current_set.push_back(j);
  11725. }
  11726. }
  11727. }
  11728. // Push the current set into new_order
  11729. for (auto c : current_set) {
  11730. new_order.push_back(graph->nodes[c]);
  11731. used_node_set.insert(graph->nodes[c]);
  11732. used[c] = true;
  11733. }
  11734. while (first_unused < graph->n_nodes && used[first_unused]) {
  11735. first_unused++;
  11736. }
  11737. }
  11738. // Replace the graph with the new order.
  11739. for (int i = 0; i < graph->n_nodes; ++i) {
  11740. graph->nodes[i] = new_order[i];
  11741. }
  11742. }
  11743. static void ggml_backend_vk_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
  11744. VK_LOG_DEBUG("ggml_backend_vk_event_record(backend=" << backend << ", event=" << event << ")");
  11745. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11746. vk_event *vkev = (vk_event *)event->context;
  11747. vk_context transfer_ctx;
  11748. if (ctx->transfer_ctx.expired()) {
  11749. // Initialize new transfer context
  11750. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11751. ctx->transfer_ctx = transfer_ctx;
  11752. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11753. } else {
  11754. transfer_ctx = ctx->transfer_ctx.lock();
  11755. }
  11756. // the backend interface doesn't have an explicit reset, so reset it here
  11757. // before we record the command to set it
  11758. ctx->device->device.resetEvent(vkev->event);
  11759. ctx->device->device.resetFences({ vkev->fence });
  11760. ggml_vk_set_event(transfer_ctx, vkev->event);
  11761. ggml_vk_ctx_end(transfer_ctx);
  11762. ggml_vk_submit(transfer_ctx, {vkev->fence});
  11763. ctx->submit_pending = true;
  11764. ctx->transfer_ctx.reset();
  11765. }
  11766. static void ggml_backend_vk_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
  11767. VK_LOG_DEBUG("ggml_backend_vk_event_wait(backend=" << backend << ", event=" << event << ")");
  11768. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11769. vk_event *vkev = (vk_event *)event->context;
  11770. vk_context transfer_ctx;
  11771. if (ctx->transfer_ctx.expired()) {
  11772. // Initialize new transfer context
  11773. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11774. ctx->transfer_ctx = transfer_ctx;
  11775. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11776. } else {
  11777. transfer_ctx = ctx->transfer_ctx.lock();
  11778. }
  11779. ggml_vk_wait_events(transfer_ctx, {vkev->event});
  11780. ggml_vk_ctx_end(transfer_ctx);
  11781. ctx->transfer_ctx.reset();
  11782. }
  11783. // TODO: enable async and synchronize
  11784. static ggml_backend_i ggml_backend_vk_interface = {
  11785. /* .get_name = */ ggml_backend_vk_name,
  11786. /* .free = */ ggml_backend_vk_free,
  11787. /* .set_tensor_async = */ ggml_backend_vk_set_tensor_async,
  11788. /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async,
  11789. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11790. /* .synchronize = */ ggml_backend_vk_synchronize,
  11791. /* .graph_plan_create = */ NULL,
  11792. /* .graph_plan_free = */ NULL,
  11793. /* .graph_plan_update = */ NULL,
  11794. /* .graph_plan_compute = */ NULL,
  11795. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11796. /* .event_record = */ ggml_backend_vk_event_record,
  11797. /* .event_wait = */ ggml_backend_vk_event_wait,
  11798. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11799. };
  11800. static ggml_guid_t ggml_backend_vk_guid() {
  11801. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11802. return &guid;
  11803. }
  11804. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11805. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11806. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11807. ggml_vk_init(ctx, dev_num);
  11808. ggml_backend_t vk_backend = new ggml_backend {
  11809. /* .guid = */ ggml_backend_vk_guid(),
  11810. /* .iface = */ ggml_backend_vk_interface,
  11811. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11812. /* .context = */ ctx,
  11813. };
  11814. if (!ctx->device->support_async) {
  11815. vk_backend->iface.get_tensor_async = nullptr;
  11816. }
  11817. return vk_backend;
  11818. }
  11819. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11820. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11821. }
  11822. int ggml_backend_vk_get_device_count() {
  11823. return ggml_vk_get_device_count();
  11824. }
  11825. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11826. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11827. int dev_idx = vk_instance.device_indices[device];
  11828. ggml_vk_get_device_description(dev_idx, description, description_size);
  11829. }
  11830. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11831. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11832. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11833. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11834. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11835. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11836. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  11837. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  11838. if (membudget_supported) {
  11839. memprops.pNext = &budgetprops;
  11840. }
  11841. vkdev.getMemoryProperties2(&memprops);
  11842. *total = 0;
  11843. *free = 0;
  11844. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11845. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11846. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  11847. *total += heap.size;
  11848. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11849. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11850. } else {
  11851. *free += heap.size;
  11852. }
  11853. }
  11854. }
  11855. }
  11856. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11857. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11858. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11859. vk::PhysicalDeviceProperties2 props = {};
  11860. device.getProperties2(&props);
  11861. return props.properties.deviceType;
  11862. }
  11863. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11864. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11865. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11866. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11867. bool ext_support = false;
  11868. for (const auto& properties : ext_props) {
  11869. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11870. ext_support = true;
  11871. break;
  11872. }
  11873. }
  11874. if (!ext_support) {
  11875. return "";
  11876. }
  11877. vk::PhysicalDeviceProperties2 props = {};
  11878. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11879. props.pNext = &pci_bus_info;
  11880. device.getProperties2(&props);
  11881. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11882. const uint32_t pci_bus = pci_bus_info.pciBus;
  11883. const uint32_t pci_device = pci_bus_info.pciDevice;
  11884. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11885. char pci_bus_id[16] = {};
  11886. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11887. return std::string(pci_bus_id);
  11888. }
  11889. //////////////////////////
  11890. struct ggml_backend_vk_device_context {
  11891. size_t device;
  11892. std::string name;
  11893. std::string description;
  11894. bool is_integrated_gpu;
  11895. std::string pci_bus_id;
  11896. };
  11897. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11898. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11899. return ctx->name.c_str();
  11900. }
  11901. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11902. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11903. return ctx->description.c_str();
  11904. }
  11905. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11906. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11907. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11908. }
  11909. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11910. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11911. return ggml_backend_vk_buffer_type(ctx->device);
  11912. }
  11913. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11914. UNUSED(dev);
  11915. return ggml_backend_vk_host_buffer_type();
  11916. }
  11917. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11918. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11919. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11920. }
  11921. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11922. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11923. props->name = ggml_backend_vk_device_get_name(dev);
  11924. props->description = ggml_backend_vk_device_get_description(dev);
  11925. props->type = ggml_backend_vk_device_get_type(dev);
  11926. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11927. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11928. props->caps = {
  11929. /* .async = */ true,
  11930. /* .host_buffer = */ true,
  11931. /* .buffer_from_host_ptr = */ false,
  11932. /* .events = */ true,
  11933. };
  11934. }
  11935. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11936. UNUSED(params);
  11937. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11938. return ggml_backend_vk_init(ctx->device);
  11939. }
  11940. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11941. switch (op->op) {
  11942. case GGML_OP_UNARY:
  11943. switch (ggml_get_unary_op(op)) {
  11944. case GGML_UNARY_OP_EXP:
  11945. case GGML_UNARY_OP_GELU:
  11946. case GGML_UNARY_OP_GELU_ERF:
  11947. case GGML_UNARY_OP_GELU_QUICK:
  11948. case GGML_UNARY_OP_SILU:
  11949. case GGML_UNARY_OP_RELU:
  11950. case GGML_UNARY_OP_XIELU:
  11951. case GGML_UNARY_OP_NEG:
  11952. case GGML_UNARY_OP_TANH:
  11953. case GGML_UNARY_OP_SIGMOID:
  11954. case GGML_UNARY_OP_HARDSIGMOID:
  11955. case GGML_UNARY_OP_HARDSWISH:
  11956. case GGML_UNARY_OP_ABS:
  11957. case GGML_UNARY_OP_SOFTPLUS:
  11958. case GGML_UNARY_OP_STEP:
  11959. case GGML_UNARY_OP_ROUND:
  11960. case GGML_UNARY_OP_CEIL:
  11961. case GGML_UNARY_OP_FLOOR:
  11962. case GGML_UNARY_OP_TRUNC:
  11963. return ggml_is_contiguous(op->src[0]) &&
  11964. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11965. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11966. (op->src[0]->type == op->type);
  11967. default:
  11968. return false;
  11969. }
  11970. case GGML_OP_GLU:
  11971. switch (ggml_get_glu_op(op)) {
  11972. case GGML_GLU_OP_GEGLU:
  11973. case GGML_GLU_OP_REGLU:
  11974. case GGML_GLU_OP_SWIGLU:
  11975. case GGML_GLU_OP_SWIGLU_OAI:
  11976. case GGML_GLU_OP_GEGLU_ERF:
  11977. case GGML_GLU_OP_GEGLU_QUICK:
  11978. return ggml_is_contiguous(op->src[0]) &&
  11979. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11980. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11981. (op->src[0]->type == op->type);
  11982. default:
  11983. return false;
  11984. }
  11985. case GGML_OP_MUL_MAT:
  11986. case GGML_OP_MUL_MAT_ID:
  11987. {
  11988. ggml_type src0_type = op->src[0]->type;
  11989. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11990. const vk_device& device = ggml_vk_get_device(ctx->device);
  11991. if (op->op == GGML_OP_MUL_MAT_ID) {
  11992. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11993. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11994. return false;
  11995. }
  11996. }
  11997. switch (src0_type) {
  11998. case GGML_TYPE_F32:
  11999. case GGML_TYPE_F16:
  12000. case GGML_TYPE_BF16:
  12001. case GGML_TYPE_Q4_0:
  12002. case GGML_TYPE_Q4_1:
  12003. case GGML_TYPE_Q5_0:
  12004. case GGML_TYPE_Q5_1:
  12005. case GGML_TYPE_Q8_0:
  12006. case GGML_TYPE_Q2_K:
  12007. case GGML_TYPE_Q3_K:
  12008. case GGML_TYPE_Q4_K:
  12009. case GGML_TYPE_Q5_K:
  12010. case GGML_TYPE_Q6_K:
  12011. case GGML_TYPE_IQ1_S:
  12012. case GGML_TYPE_IQ1_M:
  12013. case GGML_TYPE_IQ2_XXS:
  12014. case GGML_TYPE_IQ2_XS:
  12015. case GGML_TYPE_IQ2_S:
  12016. case GGML_TYPE_IQ3_XXS:
  12017. case GGML_TYPE_IQ3_S:
  12018. case GGML_TYPE_IQ4_XS:
  12019. case GGML_TYPE_IQ4_NL:
  12020. case GGML_TYPE_MXFP4:
  12021. break;
  12022. default:
  12023. return false;
  12024. }
  12025. struct ggml_tensor * a;
  12026. struct ggml_tensor * b;
  12027. if (op->op == GGML_OP_MUL_MAT) {
  12028. a = op->src[0];
  12029. b = op->src[1];
  12030. } else {
  12031. a = op->src[2];
  12032. b = op->src[1];
  12033. }
  12034. if (a->ne[3] != b->ne[3]) {
  12035. return false;
  12036. }
  12037. 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) ||
  12038. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  12039. return false;
  12040. }
  12041. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  12042. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  12043. // So don't support this combination for now.
  12044. return false;
  12045. }
  12046. return true;
  12047. }
  12048. case GGML_OP_FLASH_ATTN_EXT:
  12049. {
  12050. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12051. auto device = ggml_vk_get_device(ctx->device);
  12052. bool coopmat2 = device->coopmat2;
  12053. uint32_t HSK = op->src[1]->ne[0];
  12054. uint32_t HSV = op->src[2]->ne[0];
  12055. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  12056. return false;
  12057. }
  12058. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  12059. return false;
  12060. }
  12061. if (op->src[0]->type != GGML_TYPE_F32) {
  12062. return false;
  12063. }
  12064. if (op->type != GGML_TYPE_F32) {
  12065. return false;
  12066. }
  12067. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  12068. return false;
  12069. }
  12070. // It's straightforward to support different K/V dequant, but would
  12071. // significantly increase the number of pipelines
  12072. if (op->src[1]->type != op->src[2]->type) {
  12073. return false;
  12074. }
  12075. switch (op->src[1]->type) {
  12076. case GGML_TYPE_F16:
  12077. case GGML_TYPE_F32:
  12078. case GGML_TYPE_Q4_0:
  12079. case GGML_TYPE_Q8_0:
  12080. // supported in scalar and coopmat2 paths
  12081. break;
  12082. case GGML_TYPE_Q4_1:
  12083. case GGML_TYPE_Q5_0:
  12084. case GGML_TYPE_Q5_1:
  12085. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  12086. //case GGML_TYPE_Q2_K:
  12087. //case GGML_TYPE_Q3_K:
  12088. //case GGML_TYPE_Q4_K:
  12089. //case GGML_TYPE_Q5_K:
  12090. //case GGML_TYPE_Q6_K:
  12091. //case GGML_TYPE_IQ1_S:
  12092. //case GGML_TYPE_IQ1_M:
  12093. //case GGML_TYPE_IQ2_XXS:
  12094. //case GGML_TYPE_IQ2_XS:
  12095. //case GGML_TYPE_IQ2_S:
  12096. //case GGML_TYPE_IQ3_XXS:
  12097. //case GGML_TYPE_IQ3_S:
  12098. //case GGML_TYPE_IQ4_XS:
  12099. case GGML_TYPE_IQ4_NL:
  12100. // currently supported only in coopmat2 path
  12101. if (!coopmat2) {
  12102. return false;
  12103. }
  12104. break;
  12105. default:
  12106. return false;
  12107. }
  12108. if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) {
  12109. // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll
  12110. return false;
  12111. }
  12112. return true;
  12113. }
  12114. case GGML_OP_GET_ROWS:
  12115. {
  12116. switch (op->src[0]->type) {
  12117. case GGML_TYPE_F32:
  12118. case GGML_TYPE_F16:
  12119. case GGML_TYPE_BF16:
  12120. case GGML_TYPE_Q4_0:
  12121. case GGML_TYPE_Q4_1:
  12122. case GGML_TYPE_Q5_0:
  12123. case GGML_TYPE_Q5_1:
  12124. case GGML_TYPE_Q8_0:
  12125. case GGML_TYPE_Q2_K:
  12126. case GGML_TYPE_Q3_K:
  12127. case GGML_TYPE_Q4_K:
  12128. case GGML_TYPE_Q5_K:
  12129. case GGML_TYPE_Q6_K:
  12130. case GGML_TYPE_IQ1_S:
  12131. case GGML_TYPE_IQ1_M:
  12132. case GGML_TYPE_IQ2_XXS:
  12133. case GGML_TYPE_IQ2_XS:
  12134. case GGML_TYPE_IQ2_S:
  12135. case GGML_TYPE_IQ3_XXS:
  12136. case GGML_TYPE_IQ3_S:
  12137. case GGML_TYPE_IQ4_XS:
  12138. case GGML_TYPE_IQ4_NL:
  12139. case GGML_TYPE_MXFP4:
  12140. case GGML_TYPE_I32:
  12141. return true;
  12142. default:
  12143. return false;
  12144. }
  12145. }
  12146. case GGML_OP_SET_ROWS:
  12147. {
  12148. switch (op->type) {
  12149. case GGML_TYPE_F32:
  12150. case GGML_TYPE_F16:
  12151. case GGML_TYPE_BF16:
  12152. case GGML_TYPE_Q4_0:
  12153. case GGML_TYPE_Q4_1:
  12154. case GGML_TYPE_Q5_0:
  12155. case GGML_TYPE_Q5_1:
  12156. case GGML_TYPE_Q8_0:
  12157. case GGML_TYPE_IQ4_NL:
  12158. return true;
  12159. default:
  12160. return false;
  12161. }
  12162. }
  12163. case GGML_OP_CONT:
  12164. case GGML_OP_CPY:
  12165. case GGML_OP_DUP:
  12166. {
  12167. ggml_type src0_type = op->src[0]->type;
  12168. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  12169. if (src0_type == GGML_TYPE_F32) {
  12170. switch (src1_type) {
  12171. case GGML_TYPE_F32:
  12172. case GGML_TYPE_F16:
  12173. case GGML_TYPE_BF16:
  12174. case GGML_TYPE_Q4_0:
  12175. case GGML_TYPE_Q4_1:
  12176. case GGML_TYPE_Q5_0:
  12177. case GGML_TYPE_Q5_1:
  12178. case GGML_TYPE_Q8_0:
  12179. case GGML_TYPE_IQ4_NL:
  12180. return true;
  12181. default:
  12182. break;
  12183. }
  12184. }
  12185. if (src1_type == GGML_TYPE_F32) {
  12186. switch (src0_type) {
  12187. case GGML_TYPE_F16:
  12188. case GGML_TYPE_Q4_0:
  12189. case GGML_TYPE_Q4_1:
  12190. case GGML_TYPE_Q5_0:
  12191. case GGML_TYPE_Q5_1:
  12192. case GGML_TYPE_Q8_0:
  12193. case GGML_TYPE_IQ4_NL:
  12194. return true;
  12195. default:
  12196. break;
  12197. }
  12198. }
  12199. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  12200. return true;
  12201. }
  12202. if (
  12203. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  12204. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  12205. ) {
  12206. return true;
  12207. }
  12208. // We can handle copying from a type to the same type if it's
  12209. // either not quantized or is quantized and contiguous.
  12210. // We use f16 or f32 shaders to do the copy,
  12211. // so the type/block size must be a multiple of 4.
  12212. if (src0_type == src1_type &&
  12213. (!ggml_is_quantized(src0_type) || (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op))) &&
  12214. (ggml_type_size(src0_type) % 2) == 0) {
  12215. return true;
  12216. }
  12217. return false;
  12218. }
  12219. case GGML_OP_REPEAT:
  12220. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  12221. case GGML_OP_REPEAT_BACK:
  12222. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  12223. case GGML_OP_ROPE:
  12224. case GGML_OP_ROPE_BACK:
  12225. case GGML_OP_NONE:
  12226. case GGML_OP_RESHAPE:
  12227. case GGML_OP_VIEW:
  12228. case GGML_OP_PERMUTE:
  12229. case GGML_OP_TRANSPOSE:
  12230. case GGML_OP_RMS_NORM:
  12231. return true;
  12232. case GGML_OP_NORM:
  12233. case GGML_OP_GROUP_NORM:
  12234. case GGML_OP_L2_NORM:
  12235. return ggml_is_contiguous(op->src[0]);
  12236. case GGML_OP_ADD:
  12237. case GGML_OP_SUB:
  12238. case GGML_OP_MUL:
  12239. case GGML_OP_DIV:
  12240. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12241. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  12242. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12243. case GGML_OP_ADD_ID:
  12244. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  12245. op->type == GGML_TYPE_F32;
  12246. case GGML_OP_SILU_BACK:
  12247. case GGML_OP_RMS_NORM_BACK:
  12248. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12249. case GGML_OP_SQR:
  12250. case GGML_OP_SQRT:
  12251. case GGML_OP_SIN:
  12252. case GGML_OP_COS:
  12253. case GGML_OP_CLAMP:
  12254. return op->src[0]->type == GGML_TYPE_F32;
  12255. case GGML_OP_LEAKY_RELU:
  12256. case GGML_OP_OPT_STEP_ADAMW:
  12257. case GGML_OP_OPT_STEP_SGD:
  12258. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12259. case GGML_OP_LOG:
  12260. case GGML_OP_TRI:
  12261. case GGML_OP_DIAG:
  12262. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12263. op->type == op->src[0]->type;
  12264. case GGML_OP_ARGSORT:
  12265. {
  12266. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12267. return false;
  12268. }
  12269. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12270. auto device = ggml_vk_get_device(ctx->device);
  12271. // pipeline_argsort_large_f32 requires vulkan memory model.
  12272. if (device->vulkan_memory_model) {
  12273. return true;
  12274. } else {
  12275. return op->ne[0] <= (1 << device->max_workgroup_size_log2);
  12276. }
  12277. }
  12278. case GGML_OP_TOP_K:
  12279. {
  12280. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12281. return false;
  12282. }
  12283. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12284. auto device = ggml_vk_get_device(ctx->device);
  12285. // We could potentially support larger, using argsort to sort the
  12286. // whole thing. Not clear if this is needed.
  12287. uint32_t min_pipeline = (uint32_t)log2f(float(op->ne[0])) + 1;
  12288. if (min_pipeline >= num_topk_pipelines ||
  12289. !device->pipeline_topk_f32[min_pipeline]) {
  12290. return false;
  12291. }
  12292. }
  12293. return true;
  12294. case GGML_OP_UPSCALE:
  12295. if (op->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS) {
  12296. if ((op->op_params[0] & 0xFF) != GGML_SCALE_MODE_BILINEAR) {
  12297. return false;
  12298. }
  12299. }
  12300. return op->src[0]->type == GGML_TYPE_F32;
  12301. case GGML_OP_ACC:
  12302. return op->src[0]->type == GGML_TYPE_F32;
  12303. case GGML_OP_CONCAT:
  12304. return ggml_type_size(op->src[0]->type) == ggml_type_size(GGML_TYPE_F32);
  12305. case GGML_OP_ADD1:
  12306. return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32)
  12307. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32)
  12308. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16);
  12309. case GGML_OP_ARANGE:
  12310. case GGML_OP_FILL:
  12311. return op->type == GGML_TYPE_F32;
  12312. case GGML_OP_SCALE:
  12313. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12314. case GGML_OP_PAD:
  12315. case GGML_OP_ROLL:
  12316. return op->src[0]->type == GGML_TYPE_F32;
  12317. case GGML_OP_DIAG_MASK_INF:
  12318. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12319. case GGML_OP_SOFT_MAX:
  12320. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12321. && (!op->src[1] || (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16));
  12322. case GGML_OP_SOFT_MAX_BACK:
  12323. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12324. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32;
  12325. case GGML_OP_SUM:
  12326. case GGML_OP_SUM_ROWS:
  12327. case GGML_OP_MEAN:
  12328. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12329. case GGML_OP_CUMSUM:
  12330. {
  12331. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12332. auto device = ggml_vk_get_device(ctx->device);
  12333. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  12334. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12335. }
  12336. return false;
  12337. }
  12338. case GGML_OP_SOLVE_TRI:
  12339. {
  12340. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12341. const vk_device& device = ggml_vk_get_device(ctx->device);
  12342. if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32) {
  12343. return false;
  12344. }
  12345. const uint32_t N = op->src[0]->ne[0];
  12346. const uint32_t K = op->src[1]->ne[0];
  12347. // K dimension limited to workgroup size
  12348. if (K > 1u << device->max_workgroup_size_log2) {
  12349. return false;
  12350. }
  12351. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((N + K) * sizeof(float));
  12352. if (batch_N == 0) {
  12353. return false;
  12354. }
  12355. return true;
  12356. }
  12357. case GGML_OP_ARGMAX:
  12358. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12359. case GGML_OP_COUNT_EQUAL:
  12360. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_I32
  12361. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_I32;
  12362. case GGML_OP_IM2COL:
  12363. return ggml_is_contiguous(op->src[1])
  12364. && op->src[1]->type == GGML_TYPE_F32
  12365. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12366. case GGML_OP_IM2COL_3D:
  12367. return op->src[1]->type == GGML_TYPE_F32
  12368. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12369. case GGML_OP_TIMESTEP_EMBEDDING:
  12370. return op->src[0]->type == GGML_TYPE_F32;
  12371. case GGML_OP_CONV_2D_DW:
  12372. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16)
  12373. && op->src[1]->type == GGML_TYPE_F32;
  12374. case GGML_OP_POOL_2D:
  12375. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12376. case GGML_OP_RWKV_WKV6:
  12377. case GGML_OP_RWKV_WKV7:
  12378. return true; // all inputs are contiguous, see ggml.c
  12379. case GGML_OP_SSM_SCAN:
  12380. {
  12381. for (int i = 0; i < 6; i++) {
  12382. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  12383. return false;
  12384. }
  12385. }
  12386. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  12387. return false;
  12388. }
  12389. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  12390. return false;
  12391. }
  12392. const uint32_t d_state = op->src[0]->ne[0];
  12393. const uint32_t head_dim = op->src[0]->ne[1];
  12394. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  12395. if (!is_mamba2) {
  12396. return false;
  12397. }
  12398. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  12399. return false;
  12400. }
  12401. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12402. const vk_device& device = ggml_vk_get_device(ctx->device);
  12403. const uint32_t SPLIT_H = 16;
  12404. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  12405. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  12406. return false;
  12407. }
  12408. return true;
  12409. }
  12410. case GGML_OP_SSM_CONV:
  12411. return op->src[0]->type == GGML_TYPE_F32;
  12412. case GGML_OP_CONV_TRANSPOSE_1D:
  12413. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  12414. case GGML_OP_CONV_2D:
  12415. case GGML_OP_CONV_TRANSPOSE_2D:
  12416. {
  12417. // Channel-contiguous format is not supported yet.
  12418. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12419. op->src[1]->type == GGML_TYPE_F32 &&
  12420. op->type == GGML_TYPE_F32 &&
  12421. ggml_is_contiguous(op->src[0]) &&
  12422. ggml_is_contiguous(op->src[1]) &&
  12423. ggml_is_contiguous(op));
  12424. }
  12425. default:
  12426. return false;
  12427. }
  12428. UNUSED(dev);
  12429. }
  12430. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  12431. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  12432. return false;
  12433. }
  12434. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12435. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  12436. return buft_ctx->device->idx == ctx->device;
  12437. }
  12438. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12439. const int min_batch_size = 32;
  12440. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  12441. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  12442. UNUSED(dev);
  12443. }
  12444. static ggml_backend_event_t ggml_backend_vk_device_event_new(ggml_backend_dev_t dev) {
  12445. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12446. auto device = ggml_vk_get_device(ctx->device);
  12447. vk_event *vkev = new vk_event;
  12448. if (!vkev) {
  12449. return nullptr;
  12450. }
  12451. // The event/fence is expected to initially be in the signaled state.
  12452. vkev->event = device->device.createEvent({});
  12453. vkev->fence = device->device.createFence({vk::FenceCreateFlagBits::eSignaled});
  12454. device->device.setEvent(vkev->event);
  12455. return new ggml_backend_event {
  12456. /* .device = */ dev,
  12457. /* .context = */ vkev,
  12458. };
  12459. }
  12460. static void ggml_backend_vk_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  12461. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12462. auto device = ggml_vk_get_device(ctx->device);
  12463. vk_event *vkev = (vk_event *)event->context;
  12464. device->device.destroyFence(vkev->fence);
  12465. device->device.destroyEvent(vkev->event);
  12466. delete vkev;
  12467. delete event;
  12468. }
  12469. static void ggml_backend_vk_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  12470. VK_LOG_DEBUG("ggml_backend_vk_device_event_synchronize(backend=" << dev << ", event=" << event << ")");
  12471. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12472. auto device = ggml_vk_get_device(ctx->device);
  12473. vk_event *vkev = (vk_event *)event->context;
  12474. VK_CHECK(device->device.waitForFences({ vkev->fence }, true, UINT64_MAX), "event_synchronize");
  12475. }
  12476. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  12477. /* .get_name = */ ggml_backend_vk_device_get_name,
  12478. /* .get_description = */ ggml_backend_vk_device_get_description,
  12479. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  12480. /* .get_type = */ ggml_backend_vk_device_get_type,
  12481. /* .get_props = */ ggml_backend_vk_device_get_props,
  12482. /* .init_backend = */ ggml_backend_vk_device_init,
  12483. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  12484. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  12485. /* .buffer_from_host_ptr = */ NULL,
  12486. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  12487. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  12488. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  12489. /* .event_new = */ ggml_backend_vk_device_event_new,
  12490. /* .event_free = */ ggml_backend_vk_device_event_free,
  12491. /* .event_synchronize = */ ggml_backend_vk_device_event_synchronize,
  12492. };
  12493. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  12494. UNUSED(reg);
  12495. return GGML_VK_NAME;
  12496. }
  12497. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  12498. UNUSED(reg);
  12499. return ggml_backend_vk_get_device_count();
  12500. }
  12501. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  12502. static std::vector<ggml_backend_dev_t> devices;
  12503. static bool initialized = false;
  12504. {
  12505. static std::mutex mutex;
  12506. std::lock_guard<std::mutex> lock(mutex);
  12507. if (!initialized) {
  12508. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  12509. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  12510. char desc[256];
  12511. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  12512. ctx->device = i;
  12513. ctx->name = GGML_VK_NAME + std::to_string(i);
  12514. ctx->description = desc;
  12515. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  12516. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  12517. devices.push_back(new ggml_backend_device {
  12518. /* .iface = */ ggml_backend_vk_device_i,
  12519. /* .reg = */ reg,
  12520. /* .context = */ ctx,
  12521. });
  12522. }
  12523. initialized = true;
  12524. }
  12525. }
  12526. GGML_ASSERT(device < devices.size());
  12527. return devices[device];
  12528. }
  12529. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  12530. /* .get_name = */ ggml_backend_vk_reg_get_name,
  12531. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  12532. /* .get_device = */ ggml_backend_vk_reg_get_device,
  12533. /* .get_proc_address = */ NULL,
  12534. };
  12535. ggml_backend_reg_t ggml_backend_vk_reg() {
  12536. static ggml_backend_reg reg = {
  12537. /* .api_version = */ GGML_BACKEND_API_VERSION,
  12538. /* .iface = */ ggml_backend_vk_reg_i,
  12539. /* .context = */ nullptr,
  12540. };
  12541. try {
  12542. ggml_vk_instance_init();
  12543. return &reg;
  12544. } catch (const vk::SystemError& e) {
  12545. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  12546. return nullptr;
  12547. } catch (const std::exception &e) {
  12548. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  12549. return nullptr;
  12550. } catch (...) {
  12551. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  12552. return nullptr;
  12553. }
  12554. }
  12555. // Extension availability
  12556. static bool ggml_vk_instance_layer_settings_available() {
  12557. #ifdef GGML_VULKAN_VALIDATE
  12558. // Check if validation layer provides the extension
  12559. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  12560. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  12561. if (layer_name == layer.layerName.data()) {
  12562. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  12563. if (strcmp("VK_EXT_layer_settings", ext.extensionName.data()) == 0) {
  12564. return true;
  12565. }
  12566. }
  12567. }
  12568. }
  12569. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_layer_settings not found." << std::endl;
  12570. #endif
  12571. return false;
  12572. }
  12573. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  12574. #ifdef __APPLE__
  12575. // Check for portability enumeration extension for MoltenVK support
  12576. for (const auto& properties : instance_extensions) {
  12577. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  12578. return true;
  12579. }
  12580. }
  12581. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  12582. #endif
  12583. return false;
  12584. UNUSED(instance_extensions);
  12585. }
  12586. // Extension availability
  12587. static bool ggml_vk_instance_debug_utils_ext_available(
  12588. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  12589. // Check for portability enumeration extension for MoltenVK support
  12590. for (const auto & properties : instance_extensions) {
  12591. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  12592. return true;
  12593. }
  12594. }
  12595. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  12596. return false;
  12597. UNUSED(instance_extensions);
  12598. }
  12599. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  12600. VkPhysicalDeviceFeatures2 device_features2;
  12601. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  12602. VkPhysicalDeviceVulkan11Features vk11_features;
  12603. vk11_features.pNext = nullptr;
  12604. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  12605. device_features2.pNext = &vk11_features;
  12606. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  12607. return vk11_features.storageBuffer16BitAccess;
  12608. }
  12609. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  12610. switch (props.vendorID) {
  12611. case VK_VENDOR_ID_INTEL:
  12612. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  12613. // while some older hardware (ex. Arc A770) has performance regressions
  12614. return arch == vk_device_architecture::INTEL_XE2;
  12615. case VK_VENDOR_ID_AMD:
  12616. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  12617. // Workaround for AMD proprietary driver reporting support on all GPUs
  12618. return arch == vk_device_architecture::AMD_RDNA3;
  12619. }
  12620. return true;
  12621. default:
  12622. return true;
  12623. }
  12624. }
  12625. // checks
  12626. #ifdef GGML_VULKAN_CHECK_RESULTS
  12627. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  12628. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  12629. return;
  12630. }
  12631. for (int j = 0; j < level; j++) {
  12632. std::cerr << " ";
  12633. }
  12634. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  12635. done.push_back(tensor);
  12636. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12637. if (tensor->src[i] != nullptr) {
  12638. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  12639. }
  12640. }
  12641. }
  12642. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  12643. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  12644. return;
  12645. }
  12646. i0 = std::max(i0, 5);
  12647. i1 = std::max(i1, 5);
  12648. i2 = std::max(i2, 0);
  12649. i3 = std::max(i3, 0);
  12650. fprintf(stderr, " ");
  12651. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12652. fprintf(stderr, "%7d ", idx1);
  12653. }
  12654. fprintf(stderr, "\n");
  12655. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12656. fprintf(stderr, "%7d: ", idx0);
  12657. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12658. 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]) {
  12659. float val;
  12660. if (tensor->type == GGML_TYPE_F32) {
  12661. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12662. } else if (tensor->type == GGML_TYPE_F16) {
  12663. 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]));
  12664. } else if (tensor->type == GGML_TYPE_I32) {
  12665. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12666. } else {
  12667. GGML_ABORT("fatal error");
  12668. }
  12669. fprintf(stderr, "% 7.2f ", val);
  12670. } else {
  12671. fprintf(stderr, " ");
  12672. }
  12673. }
  12674. fprintf(stderr, "\n");
  12675. }
  12676. }
  12677. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  12678. void * tensor_data = tensor->data;
  12679. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  12680. if (is_gpu) {
  12681. const size_t tensor_size = ggml_nbytes(tensor);
  12682. tensor_data = malloc(tensor_size);
  12683. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12684. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  12685. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  12686. }
  12687. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  12688. 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;
  12689. if (tensor->src[0] != nullptr) {
  12690. 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;
  12691. }
  12692. if (tensor->src[1] != nullptr) {
  12693. 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;
  12694. }
  12695. std::cerr << std::endl << "Result:" << std::endl;
  12696. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12697. std::cerr << std::endl;
  12698. std::vector<const ggml_tensor *> done;
  12699. ggml_vk_print_graph_origin(tensor, done);
  12700. if (is_gpu) {
  12701. free(tensor_data);
  12702. }
  12703. }
  12704. void * comp_result;
  12705. size_t comp_size;
  12706. size_t comp_nb[GGML_MAX_DIMS];
  12707. size_t check_counter = 0;
  12708. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12709. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12710. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12711. return;
  12712. }
  12713. check_counter++;
  12714. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12715. return;
  12716. }
  12717. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12718. struct ggml_init_params iparams = {
  12719. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12720. /*.mem_buffer =*/ NULL,
  12721. /*.no_alloc =*/ false,
  12722. };
  12723. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12724. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12725. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12726. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  12727. std::vector<void *> cloned_mallocs;
  12728. struct ggml_tensor * tensor_clone = nullptr;
  12729. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  12730. tensor = cgraph->nodes[tensor_idx + f];
  12731. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12732. ggml_tensor * srci = tensor->src[i];
  12733. if (srci == nullptr) {
  12734. continue;
  12735. }
  12736. // If a src tensor has been cloned, use that one
  12737. auto it = cloned_tensors.find(srci);
  12738. if (it != cloned_tensors.end()) {
  12739. src_clone[i] = it->second;
  12740. continue;
  12741. }
  12742. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12743. size_t srci_size = ggml_nbytes(srci);
  12744. src_clone[i] = srci_clone;
  12745. void *src_buffer = malloc(srci_size);
  12746. cloned_mallocs.push_back(src_buffer);
  12747. srci_clone->data = src_buffer;
  12748. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12749. memcpy(srci_clone->data, srci->data, srci_size);
  12750. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12751. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12752. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12753. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12754. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12755. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12756. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12757. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12758. const int idx = i3*srci->ne[2] + i2;
  12759. 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]);
  12760. }
  12761. }
  12762. srci_clone->nb[0] = srci->nb[0];
  12763. srci_clone->nb[1] = srci->nb[1];
  12764. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12765. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12766. }
  12767. } else {
  12768. if (offset + srci_size >= buffer_gpu->size) {
  12769. srci_size = buffer_gpu->size - offset;
  12770. }
  12771. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12772. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12773. }
  12774. } else {
  12775. GGML_ABORT("fatal error");
  12776. }
  12777. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12778. ggml_vk_print_tensor(srci, srci_name[i]);
  12779. }
  12780. }
  12781. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12782. const float * params = (const float *)tensor->op_params;
  12783. 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]);
  12784. if (src_clone[4]) {
  12785. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12786. }
  12787. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12788. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12789. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12790. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12791. } else if (tensor->op == GGML_OP_SUB) {
  12792. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12793. } else if (tensor->op == GGML_OP_MUL) {
  12794. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12795. } else if (tensor->op == GGML_OP_DIV) {
  12796. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12797. } else if (tensor->op == GGML_OP_CONCAT) {
  12798. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12799. } else if (tensor->op == GGML_OP_UPSCALE) {
  12800. 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]);
  12801. } else if (tensor->op == GGML_OP_SCALE) {
  12802. const float * params = (const float *)tensor->op_params;
  12803. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12804. } else if (tensor->op == GGML_OP_ADD1) {
  12805. tensor_clone = ggml_add1(ggml_ctx, src_clone[0], src_clone[1]);
  12806. } else if (tensor->op == GGML_OP_ARANGE) {
  12807. const float start = ggml_get_op_params_f32(tensor, 0);
  12808. const float stop = ggml_get_op_params_f32(tensor, 1);
  12809. const float step = ggml_get_op_params_f32(tensor, 2);
  12810. tensor_clone = ggml_arange(ggml_ctx, start, stop, step);
  12811. } else if (tensor->op == GGML_OP_FILL) {
  12812. const float value = ggml_get_op_params_f32(tensor, 0);
  12813. tensor_clone = ggml_fill(ggml_ctx, tensor_clone, value);
  12814. } else if (tensor->op == GGML_OP_SQR) {
  12815. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12816. } else if (tensor->op == GGML_OP_SQRT) {
  12817. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12818. } else if (tensor->op == GGML_OP_SIN) {
  12819. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12820. } else if (tensor->op == GGML_OP_COS) {
  12821. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12822. } else if (tensor->op == GGML_OP_LOG) {
  12823. tensor_clone = ggml_log(ggml_ctx, src_clone[0]);
  12824. } else if (tensor->op == GGML_OP_TRI) {
  12825. tensor_clone = ggml_tri(ggml_ctx, src_clone[0], (ggml_tri_type)ggml_get_op_params_i32(tensor, 0));
  12826. } else if (tensor->op == GGML_OP_DIAG) {
  12827. tensor_clone = ggml_diag(ggml_ctx, src_clone[0]);
  12828. } else if (tensor->op == GGML_OP_CLAMP) {
  12829. const float * params = (const float *)tensor->op_params;
  12830. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12831. } else if (tensor->op == GGML_OP_PAD) {
  12832. 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],
  12833. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12834. } else if (tensor->op == GGML_OP_REPEAT) {
  12835. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12836. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12837. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12838. } else if (tensor->op == GGML_OP_ADD) {
  12839. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12840. } else if (tensor->op == GGML_OP_ACC) {
  12841. 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]);
  12842. } else if (tensor->op == GGML_OP_NORM) {
  12843. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12844. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12845. const float * float_params = (const float *)tensor->op_params;
  12846. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12847. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12848. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12849. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12850. const float eps = ((float *) tensor->op_params)[0];
  12851. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12852. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12853. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12854. } else if (tensor->op == GGML_OP_L2_NORM) {
  12855. const float eps = ((float *) tensor->op_params)[0];
  12856. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12857. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12858. if (tensor->src[1] != nullptr) {
  12859. const float * params = (const float *)tensor->op_params;
  12860. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12861. } else {
  12862. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12863. }
  12864. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12865. 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]);
  12866. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12867. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12868. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12869. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12870. const int mode = ((int32_t *) tensor->op_params)[2];
  12871. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12872. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12873. const float freq_base = ((float *) tensor->op_params)[5];
  12874. const float freq_scale = ((float *) tensor->op_params)[6];
  12875. const float ext_factor = ((float *) tensor->op_params)[7];
  12876. const float attn_factor = ((float *) tensor->op_params)[8];
  12877. const float beta_fast = ((float *) tensor->op_params)[9];
  12878. const float beta_slow = ((float *) tensor->op_params)[10];
  12879. if (mode & GGML_ROPE_TYPE_MROPE) {
  12880. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12881. if (tensor->op == GGML_OP_ROPE) {
  12882. 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);
  12883. } else {
  12884. 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);
  12885. }
  12886. } else {
  12887. if (tensor->op == GGML_OP_ROPE) {
  12888. 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);
  12889. } else {
  12890. 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);
  12891. }
  12892. }
  12893. } else if (tensor->op == GGML_OP_UNARY) {
  12894. switch (ggml_get_unary_op(tensor)) {
  12895. case GGML_UNARY_OP_EXP:
  12896. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12897. break;
  12898. case GGML_UNARY_OP_SILU:
  12899. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12900. break;
  12901. case GGML_UNARY_OP_GELU:
  12902. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12903. break;
  12904. case GGML_UNARY_OP_GELU_ERF:
  12905. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12906. break;
  12907. case GGML_UNARY_OP_GELU_QUICK:
  12908. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12909. break;
  12910. case GGML_UNARY_OP_RELU:
  12911. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12912. break;
  12913. case GGML_UNARY_OP_XIELU:
  12914. tensor_clone = ggml_xielu(ggml_ctx, src_clone[0], 0, 0, 0, 0);
  12915. ggml_set_op_params_f32(tensor_clone, 1, ggml_get_op_params_f32(tensor, 1));
  12916. ggml_set_op_params_f32(tensor_clone, 2, ggml_get_op_params_f32(tensor, 2));
  12917. ggml_set_op_params_f32(tensor_clone, 3, ggml_get_op_params_f32(tensor, 3));
  12918. ggml_set_op_params_f32(tensor_clone, 4, ggml_get_op_params_f32(tensor, 4));
  12919. break;
  12920. case GGML_UNARY_OP_NEG:
  12921. tensor_clone = ggml_neg(ggml_ctx, src_clone[0]);
  12922. break;
  12923. case GGML_UNARY_OP_TANH:
  12924. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12925. break;
  12926. case GGML_UNARY_OP_SIGMOID:
  12927. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12928. break;
  12929. case GGML_UNARY_OP_HARDSIGMOID:
  12930. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12931. break;
  12932. case GGML_UNARY_OP_HARDSWISH:
  12933. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12934. break;
  12935. case GGML_UNARY_OP_ABS:
  12936. tensor_clone = ggml_abs(ggml_ctx, src_clone[0]);
  12937. break;
  12938. case GGML_UNARY_OP_SOFTPLUS:
  12939. tensor_clone = ggml_softplus(ggml_ctx, src_clone[0]);
  12940. break;
  12941. case GGML_UNARY_OP_STEP:
  12942. tensor_clone = ggml_step(ggml_ctx, src_clone[0]);
  12943. break;
  12944. case GGML_UNARY_OP_ROUND:
  12945. tensor_clone = ggml_round(ggml_ctx, src_clone[0]);
  12946. break;
  12947. case GGML_UNARY_OP_CEIL:
  12948. tensor_clone = ggml_ceil(ggml_ctx, src_clone[0]);
  12949. break;
  12950. case GGML_UNARY_OP_FLOOR:
  12951. tensor_clone = ggml_floor(ggml_ctx, src_clone[0]);
  12952. break;
  12953. case GGML_UNARY_OP_TRUNC:
  12954. tensor_clone = ggml_trunc(ggml_ctx, src_clone[0]);
  12955. break;
  12956. default:
  12957. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12958. GGML_ABORT("fatal error");
  12959. }
  12960. } else if (tensor->op == GGML_OP_GLU) {
  12961. if (src_clone[1] == nullptr) {
  12962. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12963. } else {
  12964. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12965. }
  12966. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12967. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12968. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12969. if (tensor->src[1] == nullptr) {
  12970. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12971. tensor_clone->type = tensor->type;
  12972. } else {
  12973. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12974. }
  12975. } else if (tensor->op == GGML_OP_CONT) {
  12976. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12977. } else if (tensor->op == GGML_OP_RESHAPE) {
  12978. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12979. } else if (tensor->op == GGML_OP_VIEW) {
  12980. 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]);
  12981. } else if (tensor->op == GGML_OP_PERMUTE) {
  12982. int32_t * params = (int32_t *)tensor->op_params;
  12983. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12984. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12985. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12986. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12987. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12988. } else if (tensor->op == GGML_OP_ARGSORT) {
  12989. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12990. } else if (tensor->op == GGML_OP_TOP_K) {
  12991. tensor_clone = ggml_top_k(ggml_ctx, src_clone[0], tensor->ne[0]);
  12992. } else if (tensor->op == GGML_OP_SUM) {
  12993. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12994. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12995. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12996. } else if (tensor->op == GGML_OP_CUMSUM) {
  12997. tensor_clone = ggml_cumsum(ggml_ctx, src_clone[0]);
  12998. } else if (tensor->op == GGML_OP_MEAN) {
  12999. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  13000. } else if (tensor->op == GGML_OP_ARGMAX) {
  13001. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  13002. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  13003. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  13004. } else if (tensor->op == GGML_OP_SOLVE_TRI) {
  13005. tensor_clone = ggml_solve_tri(ggml_ctx, src_clone[0], src_clone[1], true, true, false);
  13006. } else if (tensor->op == GGML_OP_IM2COL) {
  13007. const int32_t s0 = tensor->op_params[0];
  13008. const int32_t s1 = tensor->op_params[1];
  13009. const int32_t p0 = tensor->op_params[2];
  13010. const int32_t p1 = tensor->op_params[3];
  13011. const int32_t d0 = tensor->op_params[4];
  13012. const int32_t d1 = tensor->op_params[5];
  13013. const bool is_2D = tensor->op_params[6] == 1;
  13014. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  13015. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  13016. const int32_t s0 = tensor->op_params[0];
  13017. const int32_t s1 = tensor->op_params[1];
  13018. const int32_t s2 = tensor->op_params[2];
  13019. const int32_t p0 = tensor->op_params[3];
  13020. const int32_t p1 = tensor->op_params[4];
  13021. const int32_t p2 = tensor->op_params[5];
  13022. const int32_t d0 = tensor->op_params[6];
  13023. const int32_t d1 = tensor->op_params[7];
  13024. const int32_t d2 = tensor->op_params[8];
  13025. const int32_t IC = tensor->op_params[9];
  13026. 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);
  13027. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  13028. const int32_t dim = tensor->op_params[0];
  13029. const int32_t max_period = tensor->op_params[1];
  13030. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  13031. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  13032. const int32_t s0 = tensor->op_params[0];
  13033. const int32_t p0 = tensor->op_params[1];
  13034. const int32_t d0 = tensor->op_params[2];
  13035. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  13036. } else if (tensor->op == GGML_OP_POOL_2D) {
  13037. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  13038. const int32_t k0 = tensor->op_params[1];
  13039. const int32_t k1 = tensor->op_params[2];
  13040. const int32_t s0 = tensor->op_params[3];
  13041. const int32_t s1 = tensor->op_params[4];
  13042. const int32_t p0 = tensor->op_params[5];
  13043. const int32_t p1 = tensor->op_params[6];
  13044. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  13045. } else if (tensor->op == GGML_OP_CONV_2D) {
  13046. const int32_t s0 = tensor->op_params[0];
  13047. const int32_t s1 = tensor->op_params[1];
  13048. const int32_t p0 = tensor->op_params[2];
  13049. const int32_t p1 = tensor->op_params[3];
  13050. const int32_t d0 = tensor->op_params[4];
  13051. const int32_t d1 = tensor->op_params[5];
  13052. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  13053. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  13054. const int32_t s0 = tensor->op_params[0];
  13055. const int32_t s1 = tensor->op_params[1];
  13056. const int32_t p0 = tensor->op_params[2];
  13057. const int32_t p1 = tensor->op_params[3];
  13058. const int32_t d0 = tensor->op_params[4];
  13059. const int32_t d1 = tensor->op_params[5];
  13060. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  13061. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  13062. const int32_t s = tensor->op_params[0];
  13063. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  13064. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  13065. const float * op_params = (const float *)tensor->op_params;
  13066. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  13067. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  13068. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  13069. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  13070. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  13071. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  13072. src_clone[4], src_clone[5], src_clone[6]);
  13073. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  13074. src_clone[0]->flags = tensor->src[0]->flags;
  13075. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  13076. src_clone[2], src_clone[3], src_clone[4]);
  13077. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  13078. src_clone[0]->flags = tensor->src[0]->flags;
  13079. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  13080. src_clone[2]);
  13081. } else if (tensor->op == GGML_OP_ADD_ID) {
  13082. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  13083. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  13084. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  13085. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  13086. } else if (tensor->op == GGML_OP_SSM_CONV) {
  13087. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  13088. } else if (tensor->op == GGML_OP_ROLL) {
  13089. const int32_t s0 = tensor->op_params[0];
  13090. const int32_t s1 = tensor->op_params[1];
  13091. const int32_t s2 = tensor->op_params[2];
  13092. const int32_t s3 = tensor->op_params[3];
  13093. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  13094. }
  13095. else {
  13096. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  13097. GGML_ABORT("fatal error");
  13098. }
  13099. cloned_tensors[tensor] = tensor_clone;
  13100. }
  13101. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  13102. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  13103. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  13104. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13105. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  13106. }
  13107. comp_size = ggml_nbytes(tensor_clone);
  13108. comp_result = malloc(comp_size);
  13109. memcpy(comp_result, tensor_clone->data, comp_size);
  13110. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13111. for (auto m : cloned_mallocs) {
  13112. free(m);
  13113. }
  13114. ggml_free(ggml_ctx);
  13115. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  13116. }
  13117. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  13118. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  13119. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  13120. return;
  13121. }
  13122. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  13123. return;
  13124. }
  13125. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  13126. ggml_tensor * src0 = tensor->src[0];
  13127. ggml_tensor * src1 = tensor->src[1];
  13128. ggml_tensor * src2 = tensor->src[2];
  13129. ggml_tensor * src3 = tensor->src[3];
  13130. void * tensor_data = tensor->data;
  13131. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13132. size_t tensor_size = ggml_nbytes(tensor);
  13133. tensor_data = malloc(tensor_size);
  13134. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  13135. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  13136. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  13137. if (offset + tensor_size >= buffer_gpu->size) {
  13138. tensor_size = buffer_gpu->size - offset;
  13139. }
  13140. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  13141. }
  13142. float first_error_result = -1.0f;
  13143. float first_error_correct = -1.0f;
  13144. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  13145. double avg_err = 0.0;
  13146. size_t counter = 0;
  13147. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  13148. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  13149. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  13150. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  13151. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  13152. float correct = 0.0f;
  13153. float result = 0.0f;
  13154. if (buffer_size_fit) {
  13155. if (tensor->type == GGML_TYPE_F32) {
  13156. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13157. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13158. } else if (tensor->type == GGML_TYPE_F16) {
  13159. 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]));
  13160. 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]));
  13161. } else if (tensor->type == GGML_TYPE_BF16) {
  13162. 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]));
  13163. 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]));
  13164. } else if (tensor->type == GGML_TYPE_I32) {
  13165. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13166. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13167. } else if (tensor->type == GGML_TYPE_I64) {
  13168. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13169. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13170. } else {
  13171. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  13172. }
  13173. } else {
  13174. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  13175. GGML_ABORT("fatal error");
  13176. }
  13177. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  13178. 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;
  13179. 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;
  13180. if (src0 != nullptr) {
  13181. 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;
  13182. }
  13183. if (src1 != nullptr) {
  13184. 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;
  13185. }
  13186. if (src2 != nullptr) {
  13187. 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;
  13188. }
  13189. if (src3 != nullptr) {
  13190. 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;
  13191. }
  13192. 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;
  13193. std::cerr << std::endl << "Result:" << std::endl;
  13194. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  13195. std::cerr << std::endl << "Correct:" << std::endl;
  13196. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  13197. std::cerr << std::endl;
  13198. std::vector<const ggml_tensor *> done;
  13199. ggml_vk_print_graph_origin(tensor, done);
  13200. GGML_ABORT("fatal error");
  13201. }
  13202. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  13203. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  13204. first_error[0] = i0;
  13205. first_error[1] = i1;
  13206. first_error[2] = i2;
  13207. first_error[3] = i3;
  13208. first_error_result = result;
  13209. first_error_correct = correct;
  13210. }
  13211. // Special case, value is infinite, avoid NaN result in avg_err
  13212. // NaN also appears in results, if both are nan error is 0
  13213. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  13214. avg_err += std::fabs(correct - result) / denom;
  13215. }
  13216. counter++;
  13217. }
  13218. }
  13219. }
  13220. }
  13221. avg_err /= counter;
  13222. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13223. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13224. 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;
  13225. if (src0 != nullptr) {
  13226. 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;
  13227. }
  13228. if (src1 != nullptr) {
  13229. 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;
  13230. }
  13231. if (src2 != nullptr) {
  13232. 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;
  13233. }
  13234. if (src3 != nullptr) {
  13235. 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;
  13236. }
  13237. 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;
  13238. std::cerr << std::endl << "Result:" << std::endl;
  13239. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13240. std::cerr << std::endl << "Correct:" << std::endl;
  13241. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  13242. std::cerr << std::endl;
  13243. std::vector<const ggml_tensor *> done;
  13244. ggml_vk_print_graph_origin(tensor, done);
  13245. }
  13246. if (avg_err > 0.5 || std::isnan(avg_err)) {
  13247. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13248. 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;
  13249. if (src0 != nullptr) {
  13250. 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;
  13251. }
  13252. if (src1 != nullptr) {
  13253. 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;
  13254. }
  13255. if (src2 != nullptr) {
  13256. 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;
  13257. }
  13258. if (src3 != nullptr) {
  13259. 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;
  13260. }
  13261. 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;
  13262. std::cerr << std::endl << "Result:" << std::endl;
  13263. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  13264. std::cerr << std::endl << "Correct:" << std::endl;
  13265. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  13266. std::cerr << std::endl;
  13267. std::vector<const ggml_tensor *> done;
  13268. ggml_vk_print_graph_origin(tensor, done);
  13269. GGML_ABORT("fatal error");
  13270. } else {
  13271. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  13272. }
  13273. free(comp_result);
  13274. comp_result = nullptr;
  13275. comp_size = 0;
  13276. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13277. free(tensor_data);
  13278. }
  13279. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  13280. }
  13281. #endif
  13282. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)